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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章