本文介绍了文件分片上传与合并的实现代码。Controller层通过Rchunk方法接收分片数据并调用Service层处理,Service层使用ChunkUtils.createChunk保存分片文件。分片信息通过ChunkUploadDTO实体类传输,包含文件MD5、分片索引等字段。合并时先验证分片完整性,再通过mergeChunks方法将所有分片按顺序合并为完整文件,合并完成后删除临时分块。代码采用try-with-resources确保流关闭,并通过日志记录异常情况。
public R chunk(ChunkUploadDTO dto) throws IOException { chunkService.chunk(dto); return new R<>(0,"Upload success!"); }
public void chunk(ChunkUploadDTO dto) { try { dto.setUploadRootDir("分片保存路径"); ChunkUtils.createChunk(dto); } catch (Exception e) { e.printStackTrace(); } }
@Data public class ChunkUploadDTO { /** 文件唯一标识(MD5) */ private String fileMd5; /** 分片索引(从0开始) */ private Integer chunkIndex; /** 总分片数 */ private Integer chunkCount; /** 原文件名 */ private String fileName; /** 分片文件 */ private MultipartFile chunkFile; private Integer totalChunks; // 总分片数 private String uploadRootDir; }
@PostMapping("接口名") @LogApi(logType = LogType.IN, logOperation = "合并大文件", isLogParams = false, isLogDetail = false) public R merge(ChunkUploadDTO dto) { return mergeService.merge(dto); }
public R merge(ChunkUploadDTO dto) { try { String RootDir = ChunkUtils.merge("合并路径", dto.getFileMd5(), dto.getTotalChunks(), dto.getFileName()); return new R<>(RootDir ); } catch (Exception e) { e.printStackTrace(); log.error("扫描入库异常:[{}]", e.getMessage()); return new R<>(486); } }
public static String merge(String uploadRootDir,String fileMd5,Integer totalChunks,String fileName) throws Exception { // 验证所有分块是否完整 if (!validateChunks(uploadRootDir, fileMd5, totalChunks)) { log.info("Chunk incomplete"); } // 合并分块 mergeChunks(uploadRootDir + File.separatorChar, fileMd5 + File.separatorChar, fileName, totalChunks); String scanningRootDir = uploadRootDir + File.separatorChar + fileMd5 + File.separatorChar + fileName; return scanningRootDir; } private static void mergeChunks(String chunkDir, String fileDir, String fileName, int totalChunks) throws IOException { String address = chunkDir + fileDir + fileName; File outputFile = new File(address); try (FileOutputStream fos = new FileOutputStream(outputFile, false)) { for (int i = 0; i < totalChunks; i++) { File chunkFile = new File(chunkDir + fileDir + i); Files.copy(chunkFile.toPath(), fos); chunkFile.delete(); // 删除临时分块 } } }