MultipartFile.transferTo(dest) 報 FileNotFoundException

Spring Upload file 報錯FileNotFoundException

環境:

  • Springboot 2.0.4
  • JDK8
  • 內嵌 Apache Tomcat/8.5.32

表單,enctype 和 input 的type=file 即可,例子使用單文件上傳

<form enctype="multipart/form-data" method="POST"
    action="/file/fileUpload">
    圖片<input type="file" name="file" />
    <input type="submit" value="上傳" />
</form>
@Controller
@RequestMapping("/file")
public class UploadFileController {
    @Value("${file.upload.path}")
    private String path = "upload/";

    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { 
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }
}

運行在保存文件 file.transferTo(dest) 報錯
問題
dest 是相對路徑,指向 upload/doc20170816162034_001.jpg
file.transferTo 方法調用時,判斷如果是相對路徑,則使用temp目錄,爲父目錄
因此,實際保存位置爲 C:\Users\xxxx\AppData\Local\Temp\tomcat.372873030384525225.8080\work\Tomcat\localhost\ROOT\upload\doc20170816162034_001.jpg

一則,位置不對,二則沒有父目錄存在,因此產生上述錯誤。

解決辦法
transferTo 傳入參數 定義爲絕對路徑

@Controller
@RequestMapping("/file")
public class UploadFileController {
    @Value("${file.upload.path}")
    private String path = "upload/";

    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(new File(path).getAbsolutePath()+ "/" + fileName);
        if (!dest.getParentFile().exists()) { 
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }
}

另外也可以 file.getBytes() 獲得字節數組,OutputStream.write(byte[] bytes)自己寫到輸出流中。

補充方法
application.properties 中增加配置項
spring.servlet.multipart.location= # Intermediate location of uploaded files.

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