spring boot 大文件上传实现方式(二)

控制器

 

@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;
}
}
posted @ 2019-09-12 18:06  Ryan_Gao  阅读(454)  评论(0编辑  收藏  举报