1. 程式人生 > 實用技巧 >springboot單檔案上傳到指定目錄分類並返回訪問路徑

springboot單檔案上傳到指定目錄分類並返回訪問路徑

業務邏輯就不寫service層了,方便展示.還沒放到linux中測試....

yml和配置類

yuan:
  file:
    root:
      ## 定義檔案儲存的路徑
      path: D:\develop\upload\
# ..... 省略其他無關配置
spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 10MB # 設定檔案最大大小
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${yuan.file.root.path}")
    public String fileRootPath;

    /**
     * 資源對映:把請求的/archive/** 對映到該檔案根路徑
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/archive/**").addResourceLocations("file:" + fileRootPath);
    }
}

Controller層

@Api("檔案操作相關")
@RestController
public class FileController {

    @Value("${yuan.file.root.path}")
    public String fileRootPath;

    @ApiOperation("檔案上傳")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String filePath = ""; // 檔案儲存的位置
        String urlPath = "";// 檔案web瀏覽路徑
        Assert.isTrue(!file.isEmpty(), "檔案為空");
        // 原始名 以 a.jpg為例
        String originalFilename = file.getOriginalFilename();
        // 獲取字尾並拼接'/'用於分類,也可以用日期 例: suffix = "jpg/"
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1) + "/";
        // 加上時間戳生成新的檔名,防止重複 newFileName = "1595511980146a.jpg"
        String newFileName = System.currentTimeMillis() + originalFilename;
        filePath = fileRootPath + suffix + newFileName;
        System.out.println(filePath);
        try {
            File file1 = new File(filePath);
            if (!file1.exists()) file1.mkdirs(); // 要是目錄不存在,建立一個
            file.transferTo(file1);              // 儲存起來
            urlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/archive/" + suffix + newFileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(urlPath);
    }

}

結果



參考

springboot 如何上傳圖片檔案到伺服器的指定目錄