1. 程式人生 > >Springboot圖片上傳功能實現 檔案上傳

Springboot圖片上傳功能實現 檔案上傳

1、配置上傳路徑

web:
  upload-path: E:/img/ #自定義檔案上傳路徑

multipart:
  maxRequestSize: 2Mb #設定所有檔案最大記憶體
  maxFileSize: 2Mb #設定單個檔案最大記憶體

2、springboot配置類中新增配置

@Value("${web.upload-path}")
private String uploadFiltPath; // 儲存上傳檔案的路徑
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //上傳的圖片在D盤下的OTA目錄下,訪問路徑如:http://localhost:8081/OTA/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
    //其中OTA表示訪問的字首。"file:D:/OTA/"是檔案真實的儲存路徑
    registry.addResourceHandler("/img/**").addResourceLocations("file:" + uploadFiltPath);
    super.addResourceHandlers(registry);
}

3、上傳工具類

/**
 * 檔案上傳工具包
 */
public class FileUtils {

    /**
     * @param file     檔案
     * @param path     檔案存放路徑
     * @param fileName 原始檔名
     * @return
     */
    public static boolean upload(MultipartFile file, String path, String fileName) {

        // 生成新的檔名
        //String realPath = path + "/" + FileNameUtils.getFileName(fileName);
        //使用原檔名
        String realPath = path + "/" + fileName;
        File dest = new File(realPath);
        //判斷檔案父目錄是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            //儲存檔案
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}

4、controller

@RestController
public class UploadController {
    @Value("${web.upload-path}")
    private String path;

    /**
     * @param file 要上傳的檔案
     * @return
     */
    @PassToken
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {

        if (FileUtils.upload(file, path, file.getOriginalFilename())) {
            // 上傳成功,給出頁面提示
            return ResultGenerator.genSuccessResult("/img/" + file.getOriginalFilename());
        } else {
            throw new ServiceException("圖片上傳失敗");
        }
    }
}