Servlet文件上传

Servlet实现文件上传

由于步骤相对比较固定,所以本文只记录核心步骤,其他步骤一般可以想出来,想不出来去翻这一篇博客:servlet-文件上传-狂神笔记 - 你我不在年少 - 博客园 (cnblogs.com)

Servlet实现文件上传.drawio

步骤一:导入包

①commons-io依赖

②commons-fileupload依赖

image-20211023120138825

步骤二:获取DiskFileItemFactory对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 获取DiskFileItemFactory对象
*
* @param tempfile 文件临时存储路径
* @return
*/
public static DiskFileItemFactory getDiskFileItemFactory(File tempfile) {
DiskFileItemFactory factory = new DiskFileItemFactory();

//文件大于2M,由内存转存到临时文件中
factory.setSizeThreshold(1024 * 1024 * 2);
//临时文件存储路径
factory.setRepository(tempfile);

return factory;
}

步骤三:获取ServletFileUpload对象

构造方法中可以传入步骤二中获取到的DiskFileItemFactory对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 获取ServletFileUpload对象
*
* @param factory
* @return
*/
public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
ServletFileUpload upload = new ServletFileUpload(factory);

//读取单个部分标题时,设置编码格式
upload.setHeaderEncoding("utf-8");
//单个文件最大20M
upload.setFileSizeMax(1024 * 1024 * 100);
//最多上传20M
upload.setSizeMax(1024 * 1024 * 100);

//监听上传进程
upload.setProgressListener(new ProgressListener() {
@Override
public void update(long pBytesRead, long pContentLength, int pItems) {
//计算百分比
// double percentResult = (pBytesRead / (double) pContentLength);
System.out.println("总大小:" + pContentLength + " 已上传" + pBytesRead);
}
});

return upload;
}

步骤三:解析请求,获取文件,返回结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//解析请求并返回结果
public String parseUploadRequest(HttpServletRequest request, ServletFileUpload upload, String uploadPath) throws FileUploadException, IOException {
List<FileItem> fileItems = upload.parseRequest(request);
String msg = "";

for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
//如果是简单的表单字段,返回true;如果代表上传的文件,返回false
continue;
} else {
if (fileItem.getName().trim().equals("") || fileItem.getName() == null) {
//文件名不合乎规则
continue;
} else {
//文件名
String uploadFileName = fileItem.getName();
System.out.println("uploadFileName" + uploadFileName);

//一般uploadFileName是单纯的文件名,但有些浏览器也会把路径给带上去,所以这里要再过滤一下
//lastindexof找不到返回-1
//substring从下标0开始
String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
System.out.println("fileName:" + fileName);
//后缀名
String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);
System.out.println("fileExtName:" + fileExtName);

//输出到服务器上
//可能需要用到UUID
InputStream inputStream = fileItem.getInputStream();
// FileOutputStream fos = new FileOutputStream(uploadPath + "/" + fileName + "." + fileExtName);
//使用UUID确保文件名唯一性
String uuidStirng = UUID.randomUUID().toString();
FileOutputStream fos = new FileOutputStream(uploadPath + "/" + uuidStirng + "." + fileExtName);

byte[] buffer = new byte[1024 * 1024];

while (inputStream.read(buffer) > 0) {
fos.write(buffer);
}

fos.flush();
fos.close();

inputStream.close();
msg = "文件上传成功";
}
}
fileItem.delete();
}
return msg;
}

小结

步骤相对固定。但其中还会有些许其他小技巧,如:获取文件名、借助UUID编号保持文件名唯一性。

Contents
  1. 1. Servlet实现文件上传
    1. 1.1. 步骤一:导入包
    2. 1.2. 步骤二:获取DiskFileItemFactory对象
    3. 1.3. 步骤三:获取ServletFileUpload对象
    4. 1.4. 步骤三:解析请求,获取文件,返回结果
  2. 2. 小结
|