-
問題描述:
打算給自己的項(xiàng)目添加一個上傳文件保存功能,于是我使用MultipartFile.transferTo()來完成這個功能,由于我的項(xiàng)目要部署到服務(wù)器,所以我使用了相對路徑把上傳的文件保存到當(dāng)前項(xiàng)目的工作目錄下,但是報(bào)錯了?。ń^對路徑可以正常使用,找了一下午沒弄明白,第二天早上才反應(yīng)過來會不會是這個方法就不支持直接使用相對路徑,果然是猜想的這樣?。?/p>
-
當(dāng)MultipartFile的transferTo()的參數(shù)是相對路徑時,會自動拼接成一個絕對路徑,但這個絕對路徑并不是真實(shí)存在的,所以轉(zhuǎn)存時會報(bào)錯,而如果傳遞的時絕對路徑,就不會有問題。文章來源:http://www.zghlxwxcb.cn/news/detail-819329.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-819329.html
- 解決方法如下:
//修改1.寫你要保存上傳文件的相對路徑
File dir = new File("./src/main/resources/img/");
if (!dir.exists()) {
dir.mkdirs(); // 創(chuàng)建目錄
}
String realPath = dir.getCanonicalPath(); // 獲取真實(shí)路徑
//修改2
File dest = new File(realPath+"/"+fileName);
- 最后完整的代碼:
@RequestMapping("/upload")
public String upload(HttpServletRequest request, HttpServletResponse req) throws IOException {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//前端參數(shù)名
MultipartFile file = multiRequest.getFile("image");
if (file.isEmpty()) {
return "上傳失敗,請選擇文件";
}
//獲取到上傳文件名
String fileName = file.getOriginalFilename();
//修改1.寫你要保存上傳文件的相對路徑
File dir = new File("./src/main/resources/img/");
if (!dir.exists()) {
dir.mkdirs(); // 創(chuàng)建目錄
}
String realPath = dir.getCanonicalPath(); // 獲取真實(shí)路徑
// String filePath = "./src/main/resource/img/" + fileName; // 這里填寫你想要保存的路徑,例如:"images/" + fileName;
//修改2
File dest = new File(realPath+"/"+fileName);
try {
file.transferTo(dest);
// file.transferTo(dest);
req.sendRedirect("ok.html");
return fileName;
} catch (IOException e) {
e.printStackTrace();
}
return "上傳失?。?;
}
到了這里,關(guān)于SpringBoot用MultipartFile.transferTo傳遞相對路徑的問題的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!