springboot文件上传
方式1
@PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { // 获取上传的文件名 String fileName = file.getOriginalFilename(); // 保存文件到指定路径 try { file.transferTo(new File(System.getProperty("user.dir") + "/springboot-file/upload/" + fileName)); return "文件上传成功!\n\r"; } catch(IOException e) { e.printStackTrace(); return "文件上传失败!\n\r"; } }
spring:
# 文件上传配置
servlet:
multipart:
# 是否开启http上传处理
enabled: true
# 单个文件最大长度
max-file-size: 2MB
# 最大请求文件的大小
max-request-size: 10MB
# 设置临时目录
# location: F://data//temp
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
方式2
@PostMapping("/upload") public String uploadFile(HttpServletRequest request) { // 创建一个基于Apache Commons FileUpload的文件上传解析器 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); // 解析上传的文件数据 try { List<FileItem> items = fileUpload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { // 获取上传的文件名 String fileName = FilenameUtils.getName(item.getName()); // 保存文件到指定路径 item.write(new File(System.getProperty("user.dir") + "/springboot-file/upload/" + fileName)); } } return "文件上传成功!\n\r"; } catch(Exception e) { e.printStackTrace(); return "文件上传失败!\n\r"; } }
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
分片上传
@PostMapping("/upload") public void upload555(HttpServletRequest request, HttpServletResponse response) { try { // 获取ServletFileUpload // 设置缓冲区大小,先读到内存里在从内存写 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); File fileFolder = new File(System.getProperty("user.dir") + "/springboot-file/upload/"); // 如果文件夹不存在则创建 if (!fileFolder.exists() && !fileFolder.isDirectory()) { fileFolder.mkdirs(); } factory.setRepository(fileFolder); // 解析 ServletFileUpload servletFileUpload = new ServletFileUpload(factory); // 设置单个大小与最大大小 servletFileUpload.setFileSizeMax(1 * 1024 * 1024 * 1024L); servletFileUpload.setSizeMax(10 * 1024 * 1024 * 1024L); List<FileItem> items = servletFileUpload.parseRequest(request); // 获取文件信息 UploadFileInfo uploadFileInfo = new UploadFileInfo(); for (FileItem item : items) { if (item.isFormField()) { // 获取分片数据 if ("chunk".equals(item.getFieldName())) { uploadFileInfo.setCurrentChunk(Integer.parseInt(item.getString("UTF-8"))); } if ("chunks".equals(item.getFieldName())) { uploadFileInfo.setChunks(Integer.parseInt(item.getString("UTF-8"))); } if ("name".equals(item.getFieldName())) { uploadFileInfo.setFileName(item.getString("UTF-8")); } } } // 写入临时文件 // 获取文件基本信息后 for (FileItem item : items) { if (!item.isFormField()) { // 有分片需要临时目录 String tempFileName = uploadFileInfo.getFileName(); if (StringUtils.isNotBlank(tempFileName)) { if (uploadFileInfo.getCurrentChunk() != null) { tempFileName = uploadFileInfo.getCurrentChunk() + "_" + uploadFileInfo.getFileName(); } // 判断文件是否存在 File tempFile = new File(System.getProperty("user.dir") + "/springboot-file/upload/", tempFileName); // 断点续传,判断文件是否存在,若存在则不传 if (!tempFile.exists()) { item.write(tempFile); } } } } // 判断是否合并 Integer currentChunk = uploadFileInfo.getCurrentChunk(); Integer chunks = uploadFileInfo.getChunks(); String fileName = uploadFileInfo.getFileName(); // 如果当前分片等于总分片那么合并文件 if (currentChunk != null && chunks != null && currentChunk.equals(chunks - 1)) { File tempFile = new File(System.getProperty("user.dir") + "/springboot-file/upload/", fileName); try (BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(tempFile))) { // 根据之前命名规则找到所有分片 for (int i = 0; i < chunks; i++) { File file = new File(System.getProperty("user.dir") + "/springboot-file/upload/", i + "_" + fileName); // 并发情况,需要判断所有,因为可能最后一个分片传完,之前有的还没传完 while (!file.exists()) { // 不存在休眠100毫秒后在重新判断 Thread.sleep(100); } // 分片存在,读入数组中 byte[] bytes = FileUtils.readFileToByteArray(file); os.write(bytes); os.flush(); file.delete(); } os.flush(); } } // 返回结果 response.setCharacterEncoding("UTF-8"); response.getWriter().write("上传成功"); } catch (Exception e) { e.printStackTrace(); } }