上代码:
一、Controller层:
@ApiOperation("上传作品图片")
@PostMapping(value = "uploadCalligraphy")
public String uploadFile(MultipartFile[] multipartFiles){if(multipartFiles == null){
return ResultUtil.errorMsg("上传图片不能为空!");
}if(multipartFiles !=null && multipartFiles.length<=0){
return ResultUtil.errorMsg("上传图片不能为空!");
}return uploadService.uploadFile(multipartFiles);
}
二、Service业务服务层:
@Override
public String uploadFile(MultipartFile[] multipartFiles) {List<String> picUrls = new ArrayList<>();
try {
for (MultipartFile file : multipartFiles) {
String cgyUrl =this.httpBaseUrl + ossService.uploadImage(file);
picUrls.add(cgyUrl);
}
log.info(">>> Upload pic SECCUSS!And return pic url :{}", JSONObject.toJSON(picUrls));} catch (Exception e) {
log.error("xx>>> Upload pic EXCEPTION!The reason:", e);
return ResultUtil.errorMsg("上传书法图片异常!");
}Map<String, List> resultMap = new HashMap<>();
resultMap.put("picUrls", picUrls);
return ResultUtil.successMsg(resultMap);
}
三、OSS对象存储服务层
application.yml:
upload:
img:
filepath: /home/upload-file/img/test
@Value("${upload.img.filepath}")
public String imgFilePath ;@Override
public String uploadImage(MultipartFile file) throws Exception{// 获取文件后缀
String fileNameOld = file.getOriginalFilename();
String fileSuffix = fileNameOld.substring( fileNameOld.lastIndexOf("."), fileNameOld.length());// 新的文件名
String fileNameNew = System.currentTimeMillis() + "_" +new Random().nextInt(1000) + fileSuffix;//获取文件夹路径
String dataPath = DateUtil.DateTime2FormatStr(new Date(), DateUtil.DATE_FORMAT_CONCAT);
File dateFile =new File(imgFilePath + "/" + dataPath);// 如果文件夹不存在则创建
if(!dateFile .exists() && !dateFile .isDirectory()){
dateFile .mkdir();
}// 将图片存入文件夹
File targetFile = new File(dateFile, fileNameNew);//将上传的文件写到服务器上指定的文件。
file.transferTo(targetFile);String returnUrl = dataPath + "/" + fileNameNew;
return returnUrl ;
}
四、Tomcat 映射文件配置:
<Context docBase="D:\usr\local\eben\img\test" path="/img/test" reloadable="true"/>