controller层:
@PostMapping("/uploadFile")
public ServiceResult uploadFile(MultipartFile file, @RequestParam String compareType) {
return primaryService.uploadFile(file, compareType);
}
service层:
/**
* 样本文件上传
* @param file
* @param compareType
* @return
*/
@Override
public ServiceResult uploadFile(MultipartFile file, String compareType) {
ServiceResult serviceResult = new ServiceResult();
//文件名校验
List<Map<String, Object>> dataInfo = noEarthquakePrimaryResultMapper.selectDataInfo(compareType);
List<String> fileNameLists = dataInfo.stream().map(v -> v.get("file_name")).map(String::valueOf).collect(Collectors.toList());
if (fileNameLists.contains(file.getOriginalFilename())){
serviceResult.failed(null,"文件名重复,请重新命名文件名");
}else {
//文件内容校验
boolean fileCheckFlag = fileCheck(file,compareType);
if (fileCheckFlag){
try {
saveFile(file,uploadPath);
noEarthquakePrimaryResultMapper.insertDataSet(compareType,uploadPath+file.getOriginalFilename(),file.getOriginalFilename());
serviceResult.success(null,"文件上传成功");
} catch (IOException e) {
serviceResult.failed(e,"文件内容信息不符合格式规范");
}
}
}
return serviceResult;
}
@SneakyThrows
private boolean fileCheck(MultipartFile file, String compareType){
boolean flag = false;
List<String> lines = new ArrayList<>();
IoUtil.readLines(file.getInputStream(), StandardCharsets.UTF_8, lines);
List<String> typeList = Arrays.asList(compareType.split(","));
List<String> list = lines.stream().map(v -> v.trim()).map(String::valueOf).collect(Collectors.toList());
List<List<String>> fileData = list.stream().map(v -> Arrays.asList(v.split("\t"))).collect(Collectors.toList());
List<String> firstNumber = fileData.stream().map(v -> v.get(0)).distinct().map(String::valueOf).collect(Collectors.toList());
boolean equals = typeList.equals(firstNumber);
if (equals){
boolean match = fileData.stream().allMatch(v -> v.size() == 21);
if (match){
flag =true;
}
}
return flag;
}
private void saveFile(MultipartFile file, String uploadPath) throws IOException {
// 实现具体的文件保存逻辑
Files.copy(file.getInputStream(), Paths.get(uploadPath + file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING);
}
标签:map,file,serviceResult,java,String,uploadFile,List,compareType,上传
From: https://blog.csdn.net/wyb666123/article/details/142100373