transferto 文件不存在_文件上传时,MultipartFile.transferTo() 方法报 FileNotFoundException...
Spring Upload?File 報(bào)錯(cuò)FileNotFoundException
環(huán)境:
Springboot2.0.4JDK1.8內(nèi)嵌 Apache Tomcat/8.5.32
1、前端代碼
前端上傳網(wǎng)頁表單,enctype 和 input 的type=file 即可,使用單文件上傳舉例:
圖片
2、后端代碼
@RestController
@RequestMapping("/file")public classUploadFileController {
@Value("${file.upload.path}")private String path = "upload/";
@RequestMapping(value= "fileUpload", method =RequestMethod.POST)
@ResponseBodypublic String fileUpload(@RequestParam("file") MultipartFile file) {if(file.isEmpty()) {return "false";
}
String fileName=file.getOriginalFilename();
File saveFile= new File(path + "/" +fileName);if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}try{
file.transferTo(saveFile);//保存文件
return "true";
}catch(Exception e) {
e.printStackTrace();return "false";
}
}
}
3、問題分析與解決
按照上面配置運(yùn)行時(shí),在保存文件 file.transferTo(saveFile) 報(bào)錯(cuò)
3.1 問題原因分析:
saveFile是相對(duì)路徑,指向 upload/doc20170816162034_001.jpg
file.transferTo 方法調(diào)用時(shí),判斷如果是相對(duì)路徑,則使用temp目錄,為父目錄
因此,實(shí)際保存位置為 C:\Users\xxxx\AppData\Local\Temp\tomcat.372873030384525225.8080\work\Tomcat\localhost\ROOT\upload\doc20170816162034_001.jpg
一則,位置不對(duì),二則沒有父目錄存在,因此產(chǎn)生上述錯(cuò)誤。
3.2?問題解決
transferTo 傳入?yún)?shù) 定義為絕對(duì)路徑
@RestController
@RequestMapping("/file")public classUploadFileController {
@Value("${file.upload.path}")private String path = "upload/";
@RequestMapping(value= "fileUpload", method =RequestMethod.POST)
@ResponseBodypublic 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() 獲得字節(jié)數(shù)組,OutputStream.write(byte[] bytes)自己寫到輸出流中。
4、補(bǔ)充方法
application.properties 中增加配置項(xiàng)
spring.servlet.multipart.location= # Intermediate location of uploaded files.
關(guān)于上傳文件的訪問
增加一個(gè)自定義的ResourceHandler把目錄公布出去
//寫一個(gè)Java Config
@Configurationpublic class webMvcConfig implementsorg.springframework.web.servlet.config.annotation.WebMvcConfigurer{//定義在application.properties
@Value("${file.upload.path}")private String path = "upload/";public voidaddResourceHandlers(ResourceHandlerRegistry registry) {
String p= new File(path).getAbsolutePath() + File.separator;//取得在服務(wù)器中的絕對(duì)路徑
System.out.println("Mapping /upload/** from " +p);
registry.addResourceHandler("/upload/**") //外部訪問地址
.addResourceLocations("file:" + p)//springboot需要增加file協(xié)議前綴
.setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));//設(shè)置瀏覽器緩存30分鐘
}
}
application.properties 中 file.upload.path=upload/
實(shí)際存儲(chǔ)目錄
D:/upload/2019/03081625111.jpg
訪問地址(假設(shè)應(yīng)用發(fā)布在http://www.a.com/)
http://www.a.com/upload/2019/03081625111.jpg
在Controller中增加一個(gè)RequestMapping,把文件輸出到輸出流中
@RestController
@RequestMapping("/file")public classUploadFileController {
@AutowiredprotectedHttpServletRequest request;
@AutowiredprotectedHttpServletResponse response;
@AutowiredprotectedConversionService conversionService;
@Value("${file.upload.path}")private String path = "upload/";
@RequestMapping(value="/view", method =RequestMethod.GET)public Object view(@RequestParam("id") Integer id){//通常上傳的文件會(huì)有一個(gè)數(shù)據(jù)表來存儲(chǔ),這里返回的id是記錄id
UploadFile file = conversionService.convert(id, UploadFile.class);//這步也可以寫在請(qǐng)求參數(shù)中
if(file==null){throw new RuntimeException("沒有文件");
}
File source= new File(new File(path).getAbsolutePath()+ "/" +file.getPath());
response.setContentType(contentType);try{
FileCopyUtils.copy(newFileInputStream(source), response.getOutputStream());
}catch(Exception e) {
e.printStackTrace();
}return null;
}
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的transferto 文件不存在_文件上传时,MultipartFile.transferTo() 方法报 FileNotFoundException...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 1061. 判断题(15)
 - 下一篇: 运营商iptv服务器,电信运营商IPTV