步骤如下:
**1. 添加如下依赖**
```xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
```
**2. 前端上传文件**
```html
<body>
<input id="file" type="file" multiple />
<br />
<button onclick="uploadFile()">上传</button>
</body>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function uploadFile() {
const files = $("#file")[0].files
const formData = new FormData()
for (let i = 0; i < files.length; i++) {
formData.append("file", files[i])
}
formData.append("message", "上传文件")
$.ajax({
url: '/web/upload?method=uploadFile',
async: true,
method: 'post',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
beforeSend: function() {},
success: function(res) {
console.log(res)
},
error: function() {}
})
}
</script>
```
**3. Servlet代码**
```java
@WebServlet("/upload")
public class UploadServlet extends BaseServlet {
public void uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
Map<String, Object> params = new HashMap<>(1);
//检测是否为多媒体上传
if (!ServletFileUpload.isMultipartContent(request)) {
params.put("msg", "上传数据不是多媒体数据");
out.println(JSON.toJSONString(params));
out.flush();
return;
}
//配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
//内存临界值,内存每次能处理3M
factory.setSizeThreshold(1024 * 1024 * 3);
//当文件大小超过内存临界值时,设置的临时存储目录
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
//设置单个文件最大上传值为5M
upload.setFileSizeMax(1024 * 1024 * 5);
//设置最大请求值
//包含文件和表单数据,每次提交的表单总数据不能超过50M
upload.setSizeMax(1024 * 1024 * 50);
//中文处理
upload.setHeaderEncoding("UTF-8");
//解析请求的内容,将文件和表单数据分开
List<FileItem> formItems = upload.parseRequest(request);
if (CollectionUtils.isNotEmpty(formItems)) {
for (FileItem item : formItems) {
//判断是不是文件
if (!item.isFormField()) {
System.out.println("文件名:" + item.getName());
//文件名:poi01.png
//文件名:poi02.png
File storeFile = new File("e:/upload/servlet/" + item.getName());
//将文件存储到磁盘中
item.write(storeFile);
} else {
System.out.println(new String(item.get(), "UTF-8"));
//上传文件
}
}
}
params.put("msg", "上传成功");
out.println(JSON.toJSONString(params));
out.flush();
}
}
```