Spring Boot 使用 ServletFileUpload上传文件失败,upload.parseRequest(request)为空
使用Apache Commons FileUpload组件上传文件时总是返回null,调试发现ServletFileUpload对象为空,在Spring Boot中有默认的文件上传组件,在使用ServletFileUpload时需要关闭Spring Boot的默认配置 ,
禁用MultipartResolver
Spring提供的默认值
1.0在配置文件中添加
spring.http.multipart.enabled=false
2.0在配置文件中添加
spring.servlet.multipart.enabled=false
@RequestMapping("/upload") public void upload(HttpServletRequest request, HttpServletResponse response) { System.out.println("进入后台..."); // 1.创建DiskFileItemFactory对象,配置缓存用 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // 2. 创建 ServletFileUpload对象 ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // 3. 设置文件名称编码 servletFileUpload.setHeaderEncoding("utf-8"); // 4. 开始解析文件 // 文件md5获取的字符串 String fileMd5 = null; // 文件的索引 String chunk = null; try { List<FileItem> items = servletFileUpload.parseRequest(new ServletRequestContext(request)); for (FileItem fileItem : items) { if (fileItem.isFormField()) { // >> 普通数据 String fieldName = fileItem.getFieldName(); if ("info".equals(fieldName)) { String info = fileItem.getString("utf-8"); System.out.println("info:" + info); } if ("fileMd5".equals(fieldName)) { fileMd5 = fileItem.getString("utf-8"); System.out.println("fileMd5:" + fileMd5); } if ("chunk".equals(fieldName)) { chunk = fileItem.getString("utf-8"); System.out.println("chunk:" + chunk); } } else { // 如果文件夹没有创建文件夹 File file = new File(serverPath + fileMd5); if (!file.exists()) { boolean result = file.mkdirs(); System.out.println(result); } // 保存文件 File chunkFile = new File(serverPath + fileMd5 + "/" + chunk); FileUtils.copyInputStreamToFile(fileItem.getInputStream(), chunkFile); } } } catch (Exception e) { e.printStackTrace(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> 文件:<input type="file" value="请选择文件" name="file"/> <br/> 信息:<input type="text" name="info"/> <br/> <input type="submit" value="提交"/> </form> </body> </html>
我们度尽的年岁,好像一声叹息,不过是劳苦愁烦,转眼成空