1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > SpringBoot:上传文件(图片 语音)到本地服务器方案

SpringBoot:上传文件(图片 语音)到本地服务器方案

时间:2020-10-14 09:00:00

相关推荐

SpringBoot:上传文件(图片 语音)到本地服务器方案

上代码:

一、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"/>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。