springboot斷點上傳、續(xù)傳、秒傳實現方式
更新時間:2024年07月17日 08:56:59 作者:Mr-Wanter
這篇文章主要介紹了springboot斷點上傳、續(xù)傳、秒傳實現方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
前言
- springboot 斷點上傳、續(xù)傳、秒傳實現。
- 保存方式提供本地上傳(單機)和minio上傳(可集群)
- 本文主要是后端實現方案,數據庫持久化采用jpa
一、實現思路
- 前端生成文件md5,根據md5檢查文件塊上傳進度或秒傳
- 需要上傳分片的文件上傳分片文件
- 分片合并后上傳服務器
二、數據庫表對象
說明:
AbstractDomainPd<String>
為公共字段,如id,創(chuàng)建人,創(chuàng)建時間等,根據自己框架修改即可。- clientId 應用id用于隔離不同應用附件,非必須
- 附件表:上傳成功的附件信息
@Entity @Table(name = "gsdss_file", schema = "public") @Data public class AttachmentPO extends AbstractDomainPd<String> implements Serializable { /** * 相對路徑 */ private String path; /** * 文件名 */ private String fileName; /** * 文件大小 */ private String size; /** * 文件MD5 */ private String fileIdentifier; }
分片信息表:記錄當前文件已上傳的分片數據
@Entity @Table(name = "gsdss_file_chunk", schema = "public") @Data public class ChunkPO extends AbstractDomainPd<String> implements Serializable { /** * 應用id */ private String clientId; /** * 文件塊編號,從1開始 */ private Integer chunkNumber; /** * 文件標識MD5 */ private String fileIdentifier; /** * 文件名 */ private String fileName; /** * 相對路徑 */ private String path; }
三、業(yè)務入參對象
檢查文件塊上傳進度或秒傳入參對象
package com.gsafety.bg.gsdss.file.manage.model.req; import io.swagger.v3.oas.annotations.Hidden; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.web.multipart.MultipartFile; import javax.validation.constraints.NotNull; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class ChunkReq { /** * 文件塊編號,從1開始 */ @NotNull private Integer chunkNumber; /** * 文件標識MD5 */ @NotNull private String fileIdentifier; /** * 相對路徑 */ @NotNull private String path; /** * 塊內容 */ @Hidden private MultipartFile file; /** * 應用id */ @NotNull private String clientId; /** * 文件名 */ @NotNull private String fileName; }
上傳分片入參
@Data @Builder @AllArgsConstructor @NoArgsConstructor public class CheckChunkReq { /** * 應用id */ @NotNull private String clientId; /** * 文件名 */ @NotNull private String fileName; /** * md5 */ @NotNull private String fileIdentifier; }
分片合并入參
@Data @Builder @AllArgsConstructor @NoArgsConstructor public class FileReq { @Hidden private MultipartFile file; /** * 文件名 */ @NotNull private String fileName; /** * 文件大小 */ @NotNull private Long fileSize; /** * eg:data/plan/ */ @NotNull private String path; /** * md5 */ @NotNull private String fileIdentifier; /** * 應用id */ @NotNull private String clientId; }
檢查文件塊上傳進度或秒傳返回結果
@Data public class UploadResp implements Serializable { /** * 是否跳過上傳(已上傳的可以直接跳過,達到秒傳的效果) */ private boolean skipUpload = false; /** * 已經上傳的文件塊編號,可以跳過,斷點續(xù)傳 */ private List<Integer> uploadedChunks; /** * 文件信息 */ private AttachmentResp fileInfo; }
四、本地上傳實現
@Resource private S3OssProperties properties; @Resource private AttachmentService attachmentService; @Resource private ChunkDao chunkDao; @Resource private ChunkMapping chunkMapping; /** * 上傳分片文件 * * @param req */ @Override public boolean uploadChunk(ChunkReq req) { BizPreconditions.checkArgumentNoStack(!req.getFile().isEmpty(), "上傳分片不能為空!"); BizPreconditions.checkArgumentNoStack(req.getPath().endsWith("/"), "url參數必須是/結尾"); //文件名-1 String fileName = req.getFileName().concat("-").concat(req.getChunkNumber().toString()); //分片文件上傳服務器的目錄地址 文件夾地址/chunks/文件md5 String filePath = properties.getPath().concat(req.getClientId()).concat(File.separator).concat(req.getPath()) .concat("chunks").concat(File.separator).concat(req.getFileIdentifier()).concat(File.separator); try { Path newPath = Paths.get(filePath); Files.createDirectories(newPath); //文件夾地址/md5/文件名-1 newPath = Paths.get(filePath.concat(fileName)); if (Files.notExists(newPath)) { Files.createFile(newPath); } Files.write(newPath, req.getFile().getBytes(), StandardOpenOption.CREATE); } catch (IOException e) { log.error(" 附件存儲失敗 ", e); throw new BusinessCheckException("附件存儲失敗"); } // 存儲分片信息 chunkDao.save(chunkMapping.req2PO(req)); return true; } /** * 檢查文件塊 */ @Override public UploadResp checkChunk(CheckChunkReq req) { UploadResp result = new UploadResp(); //查詢數據庫記錄 //先判斷整個文件是否已經上傳過了,如果是,則告訴前端跳過上傳,實現秒傳 AttachmentResp resp = attachmentService.findByFileIdentifierAndClientId(req.getFileIdentifier(), req.getClientId()); if (resp != null) { //當前文件信息另存 AttachmentResp newResp = attachmentService.save(AttachmentReq.builder() .fileName(req.getFileName()).origin(AttachmentConstants.TYPE.LOCAL_TYPE) .clientId(req.getClientId()).path(resp.getPath()).size(resp.getSize()) .fileIdentifier(req.getFileIdentifier()).build()); result.setSkipUpload(true); result.setFileInfo(newResp); return result; } //如果完整文件不存在,則去數據庫判斷當前哪些文件塊已經上傳過了,把結果告訴前端,跳過這些文件塊的上傳,實現斷點續(xù)傳 List<ChunkPO> chunkList = chunkDao.findByFileIdentifierAndClientId(req.getFileIdentifier(), req.getClientId()); //將已存在的塊的chunkNumber列表返回給前端,前端會規(guī)避掉這些塊 if (!CollectionUtils.isEmpty(chunkList)) { List<Integer> collect = chunkList.stream().map(ChunkPO::getChunkNumber).collect(Collectors.toList()); result.setUploadedChunks(collect); } return result; } /** * 分片合并 * * @param req */ @Override public boolean mergeChunk(FileReq req) { String filename = req.getFileName(); String date = DateUtil.localDateToString(LocalDate.now()); //附件服務器存儲合并后的文件存放地址 String file = properties.getPath().concat(req.getClientId()).concat(File.separator).concat(req.getPath()) .concat(date).concat(File.separator).concat(filename); //服務器分片文件存放地址 String folder = properties.getPath().concat(req.getClientId()).concat(File.separator).concat(req.getPath()) .concat("chunks").concat(File.separator).concat(req.getFileIdentifier()); //合并文件到本地目錄,并刪除分片文件 boolean flag = mergeFile(file, folder, filename); if (!flag) { return false; } //保存文件記錄 AttachmentResp resp = attachmentService.findByFileIdentifierAndClientId(req.getFileIdentifier(), req.getClientId()); if (resp == null) { attachmentService.save(AttachmentReq.builder().fileName(filename).origin(AttachmentConstants.TYPE.LOCAL_TYPE) .clientId(req.getClientId()).path(file).size(FileUtils.changeFileFormat(req.getFileSize())) .fileIdentifier(req.getFileIdentifier()).build()); } //插入文件記錄成功后,刪除chunk表中的對應記錄,釋放空間 chunkDao.deleteAllByFileIdentifierAndClientId(req.getFileIdentifier(), req.getClientId()); return true; } /** * 文件合并 * * @param targetFile 要形成的文件地址 * @param folder 分片文件存放地址 * @param filename 文件的名稱 */ private boolean mergeFile(String targetFile, String folder, String filename) { try { //先判斷文件是否存在 if (FileUtils.fileExists(targetFile)) { //文件已存在 return true; } Path newPath = Paths.get(StringUtils.substringBeforeLast(targetFile, File.separator)); Files.createDirectories(newPath); Files.createFile(Paths.get(targetFile)); Files.list(Paths.get(folder)) .filter(path -> !path.getFileName().toString().equals(filename)) .sorted((o1, o2) -> { String p1 = o1.getFileName().toString(); String p2 = o2.getFileName().toString(); int i1 = p1.lastIndexOf("-"); int i2 = p2.lastIndexOf("-"); return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1))); }) .forEach(path -> { try { //以追加的形式寫入文件 Files.write(Paths.get(targetFile), Files.readAllBytes(path), StandardOpenOption.APPEND); //合并后刪除該塊 Files.delete(path); } catch (IOException e) { log.error(e.getMessage(), e); throw new BusinessException("文件合并失敗"); } }); //刪除空文件夾 FileUtils.delDir(folder); } catch (IOException e) { log.error("文件合并失敗: ", e); throw new BusinessException("文件合并失敗"); } return true; }
五、minio上傳實現
@Resource private MinioTemplate minioTemplate; @Resource private AttachmentService attachmentService; @Resource private ChunkDao chunkDao; @Resource private ChunkMapping chunkMapping; /** * 上傳分片文件 */ @Override public boolean uploadChunk(ChunkReq req) { String fileName = req.getFileName(); BizPreconditions.checkArgumentNoStack(!req.getFile().isEmpty(), "上傳分片不能為空!"); BizPreconditions.checkArgumentNoStack(req.getPath().endsWith(separator), "url參數必須是/結尾"); String newFileName = req.getPath().concat("chunks").concat(separator).concat(req.getFileIdentifier()).concat(separator) + fileName.concat("-").concat(req.getChunkNumber().toString()); try { minioTemplate.putObject(req.getClientId(), newFileName, req.getFile()); } catch (Exception e) { e.printStackTrace(); throw new BusinessException("文件上傳失敗"); } // 存儲分片信息 chunkDao.save(chunkMapping.req2PO(req)); return true; } /** * 檢查文件塊 */ @Override public UploadResp checkChunk(CheckChunkReq req) { UploadResp result = new UploadResp(); //查詢數據庫記錄 //先判斷整個文件是否已經上傳過了,如果是,則告訴前端跳過上傳,實現秒傳 AttachmentResp resp = attachmentService.findByFileIdentifierAndClientId(req.getFileIdentifier(), req.getClientId()); if (resp != null) { //當前文件信息另存 AttachmentResp newResp = attachmentService.save(AttachmentReq.builder() .fileName(req.getFileName()).origin(AttachmentConstants.TYPE.MINIO_TYPE) .clientId(req.getClientId()).path(resp.getPath()).size(resp.getSize()) .fileIdentifier(req.getFileIdentifier()).build()); result.setSkipUpload(true); result.setFileInfo(newResp); return result; } //如果完整文件不存在,則去數據庫判斷當前哪些文件塊已經上傳過了,把結果告訴前端,跳過這些文件塊的上傳,實現斷點續(xù)傳 List<ChunkPO> chunkList = chunkDao.findByFileIdentifierAndClientId(req.getFileIdentifier(), req.getClientId()); //將已存在的塊的chunkNumber列表返回給前端,前端會規(guī)避掉這些塊 if (!CollectionUtils.isEmpty(chunkList)) { List<Integer> collect = chunkList.stream().map(ChunkPO::getChunkNumber).collect(Collectors.toList()); result.setUploadedChunks(collect); } return result; } /** * 分片合并 * * @param req */ @Override public boolean mergeChunk(FileReq req) { String filename = req.getFileName(); //合并文件到本地目錄 String chunkPath = req.getPath().concat("chunks").concat(separator).concat(req.getFileIdentifier()).concat(separator); List<Item> chunkList = minioTemplate.getAllObjectsByPrefix(req.getClientId(), chunkPath, false); String fileHz = filename.substring(filename.lastIndexOf(".")); String newFileName = req.getPath() + UUIDUtil.uuid() + fileHz; try { List<ComposeSource> sourceObjectList = chunkList.stream() .sorted(Comparator.comparing(Item::size).reversed()) .map(l -> ComposeSource.builder() .bucket(req.getClientId()) .object(l.objectName()) .build()) .collect(Collectors.toList()); ObjectWriteResponse response = minioTemplate.composeObject(req.getClientId(), newFileName, sourceObjectList); //刪除分片bucket及文件 minioTemplate.removeObjects(req.getClientId(), chunkPath); } catch (Exception e) { e.printStackTrace(); throw new BusinessException("文件合并失敗"); } //保存文件記錄 AttachmentResp resp = attachmentService.findByFileIdentifierAndClientId(req.getFileIdentifier(), req.getClientId()); if (resp == null) { attachmentService.save(AttachmentReq.builder().fileName(filename).origin(AttachmentConstants.TYPE.MINIO_TYPE) .clientId(req.getClientId()).path(newFileName).size(FileUtils.changeFileFormat(req.getFileSize())) .fileIdentifier(req.getFileIdentifier()).build()); } //插入文件記錄成功后,刪除chunk表中的對應記錄,釋放空間 chunkDao.deleteAllByFileIdentifierAndClientId(req.getFileIdentifier(), req.getClientId()); return true; }
總結
1.檢查文件塊上傳進度或秒傳
- 根據文件md5查詢附件信息表,如果存在,直接返回附件信息。
- 不存在查詢分片信息表,查詢當前文件分片上傳進度,返回已經上傳過的分片編號
2.上傳分片
- 分片文件上傳地址需要保證唯一性,可用文件MD5作為隔離
- 上傳后保存分片上傳信息
- minio對合并分片文件有大小限制,除最后一個分片外,其他分片文件大小不得小于5MB,所以minio分片上傳需要分片大小最小為5MB,并且獲取分片需要按照分片文件大小排序,將最后一個分片放到最后進行合并
3.分片合并
- 將分片文件合并為新文件到最終文件存放地址并刪除分片文件
- 保存最終文件信息到附件信息表
- 刪除對應分片信息表數據
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解Spring Boot 使用Spring security 集成CAS
本篇文章主要介紹了詳解Spring Boot 使用Spring security 集成CAS,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05Spring Security如何使用URL地址進行權限控制
這篇文章主要介紹了Spring Security如何使用URL地址進行權限控制,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-12-12