笔记:
手动实现文件上传:
(1)获得分割线
(2)获得请求体的所有内容: request. setInputStream();
(3)利用分割线将获得内容进行分割
(4)判断是普通项还是文件上传项
普通项:获得普通项名称和值
文件上传项:获得文件名称和文件内容,通过流写到服务器上
文件上传的代码实现
一、引入文件上传的相关jar包
二、编写文件上传的页面
三、编写文件上传的Servlet
文件上传的API
DiskFileItemFactory: 磁盘文件项工厂
构造方法:
DiskFileItemFactory(
DiskFileItemFactory (int sizeThreshold, File reposi tory)
sizeThreshold:用来设置文件上传的缓冲区的大小,默认值为10KB
repository:用来设置文件上传过程中所产生的临时文件存放的路径
DiskFileItemFactory diskFileItemFactory = new DiskF ileItem
ServletFileUpload fileUpload = new ServletFileUpload( diskFileItemFactory);
fileUpload. setHeaderEncoding("UTF-8");
List<FileItem> list = fileUpload. parseRequest(request);
for(FileItem fileItem : list) {
if(fileItem. isFormField()) {
String name = fileItem. getF ieldName();
String value = fileItem. getString("UTF-8");
System. out . println(name + ":" + value);
}else {
String filename = fileItem. getName();
InputStream is = fileItem. getInputStream();
String realPath = getServletContext(). getRealPath("/upload");
OutputStream os = new FileOutputStream(realPath + "/" + filename);
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e. printStackTrace();
}