@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {
private final String UPLOAD_DIRECTORY = "/uploads";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 检查请求是否含有文件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "上传请求必须包含文件");
return;
}
// 配置上传参数
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024 * 10);
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024 * 1024 * 50);
upload.setFileSizeMax(1024 * 1024 * 10);
// 解析上传请求
List<FileItem> items;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
throw new ServletException("无法解析上传请求", e);
}
// 保存上传文件
for (FileItem item : items) {
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = getServletContext().getRealPath(UPLOAD_DIRECTORY) + File.separator + fileName;
File storeFile = new File(filePath);
item.write(storeFile);
}
}
// 发送响应
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("文件上传成功!");
}
}