spring boot 大文件上傳實現方式(二)

控制器app

 

@ApiOperation(value = "分片上傳文件")
@PostMapping("/import/upload/fragment")
@RequiresAuthentication
public Result<UploadResultModel> fragmentUpload(FragmentUploadModel uploadModel, String parentId) throws BusinessException {
return JsonSuccess(personKnowledgeService.fragmentUpload(uploadModel,parentId));
}


Service實現方法
/**
* 分片上傳文件
*
* @param uploadModel
*/
@Override
public UploadResultModel fragmentUpload(FragmentUploadModel uploadModel, String parentId) throws BusinessException {
String taskId = uploadModel.getTaskId();
//上傳臨時文件目錄
String tmpPath = ImportExportConstants.IMPORT_BASE_PATH + taskId + "/" + ImportExportConstants.PART_PATH;
CommonUtils.createDir(tmpPath);

String savePath = tmpPath + uploadModel.getChunk();

try {
Files.write(Paths.get(savePath), uploadModel.getFile().getBytes());
} catch (IOException e) {
e.printStackTrace();
return null;
}

boolean checkResult = checkIsUploadComplete(uploadModel);
if (checkResult) {
mergeAndAnalysis(uploadModel);
addPersonKnowledgeRecord(uploadModel, parentId);
}
UploadResultModel resultModel = new UploadResultModel();
resultModel.setChunks(uploadModel.getChunks());
resultModel.setOriginalFilename(uploadModel.getFile().getOriginalFilename());
resultModel.setPart(uploadModel.getPart());
resultModel.setTaskId(uploadModel.getTaskId());

return resultModel;
}

/**
* 檢查是否上傳完成
*
* @param uploadModel
* @return
*/
private boolean checkIsUploadComplete(FragmentUploadModel uploadModel) {
String taskId = uploadModel.getTaskId();
//上傳臨時文件目錄
String basePath = ImportExportConstants.IMPORT_BASE_PATH + taskId + "/";

File partDir = new File(basePath + ImportExportConstants.PART_PATH);


File[] files = partDir.listFiles();
if (files == null || files.length != uploadModel.getChunks()) {
return false;
}
return true;
}

/**
* 合併上傳文件分片並解析
*
* @param uploadModel
* @return
*/
@Override
public void mergeAndAnalysis(FragmentUploadModel uploadModel) throws BusinessException {
String taskId = uploadModel.getTaskId();
//上傳臨時文件目錄
String basePath = ImportExportConstants.IMPORT_BASE_PATH + taskId + "/";

//合併分片
File mergeFile = mergeFiles(basePath, uploadModel);

File baseDir = new File(basePath);
File[] files = baseDir.listFiles();

if (files == null) {
throw new BusinessException(OpsErrorMessage.MODULE_NAME, OpsErrorMessage.ERROR_MESSAGE, "內容爲空!");
}
}

private File mergeFiles(String basePath, FragmentUploadModel uploadModel) throws BusinessException {
File partDir = new File(basePath + ImportExportConstants.PART_PATH);
File destFile = new File(basePath + uploadModel.getName());


File[] files = partDir.listFiles();
if (files == null || files.length != uploadModel.getChunks()) {
throw new BusinessException(OpsErrorMessage.MODULE_NAME, OpsErrorMessage.ERROR_MESSAGE, "文件上傳失敗!");
}

try (FileOutputStream out = new FileOutputStream(destFile, true)) {
List<File> parts = Lists.newArrayList(files);
parts.sort(Comparator.comparingInt(o -> Integer.valueOf(o.getName())));

for (File part : parts) {
FileUtils.copyFile(part, out);
}
} catch (Exception e) {
throw new BusinessException(OpsErrorMessage.MODULE_NAME, OpsErrorMessage.ERROR_MESSAGE, "文件上傳失敗!");
} finally {
//刪除分片文件
try {
FileUtils.deleteDirectory(partDir);
} catch (IOException e) {
e.printStackTrace();
}
}

return destFile;
}

private void addPersonKnowledgeRecord(FragmentUploadModel uploadModel, String parentId) {
String taskId = uploadModel.getTaskId();
//上傳臨時文件目錄
String basePath = ImportExportConstants.IMPORT_BASE_PATH + taskId + "/";
//添加記錄
String fileName = uploadModel.getName();
PersonKnowledge model = new PersonKnowledge();
model.setCreateTime(new Date());
model.setCreateId(SecurityUtils.getSubject().getCurrentUser().getId());
if (StringUtils.isEmpty(parentId)) {
parentId = "ROOT";
}
model.setParentId(parentId);
model.setAttchmentType(PersonKnowledgeType.文件.getId());
String suffixName = fileName.substring(fileName.lastIndexOf("."));
model.setName(fileName.substring(0, fileName.lastIndexOf("."))); // 新文件名
model.setAttachmentPath(basePath + fileName); //文件路徑
model.setSuffix(suffixName.toLowerCase().substring(1));
//獲取文件大小
Long size = uploadModel.getSize();
String fileSizeString = "";
DecimalFormat df = new DecimalFormat("#.00");
if (size != null) {
if (size < 1024) {
fileSizeString = df.format((double) size) + "B";
model.setFileSize(fileSizeString);
} else if (size < 1048576) {
fileSizeString = df.format((double) size / 1024) + "K";
model.setFileSize(fileSizeString);
} else if (size < 1073741824) {
fileSizeString = df.format((double) size / 1048576) + "M";
model.setFileSize(fileSizeString);
} else {
fileSizeString = df.format((double) size / 1073741824) + "G";
model.setFileSize(fileSizeString);
}
}
personKnowledgeRepository.save(model);
}

參數Model
@ApiModel(description = "分片上傳文件模型")public class FragmentUploadModel {    /**     * 分片上傳文件     */    @ApiModelProperty(value = "分片上傳文件")    private MultipartFile file;    /**     * 上傳任務id     */    @ApiModelProperty(value = "上傳任務id")    private String taskId;    /**     * 分片數     */    @ApiModelProperty(value = "分片數")    private Integer chunks;    /**     * 分片號     */    @ApiModelProperty(value = "分片號")    private Integer chunk;    @ApiModelProperty(value = "文件名")    private String name;    @ApiModelProperty(value = "文件大小")    private Long size;    private String part;    public Integer getChunk() {        return chunk;    }    public void setChunk(Integer chunk) {        this.chunk = chunk;    }    public MultipartFile getFile() {        return file;    }    public void setFile(MultipartFile file) {        this.file = file;    }    public String getTaskId() {        return taskId;    }    public void setTaskId(String taskId) {        this.taskId = taskId;    }    public Integer getChunks() {        return chunks;    }    public void setChunks(Integer chunks) {        this.chunks = chunks;    }    public String getPart() {        return part;    }    public void setPart(String part) {        this.part = part;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Long getSize() {        return size;    }    public void setSize(Long size) {        this.size = size;    }}
相關文章
相關標籤/搜索