Spring Upload file 报错FileNotFoundException
表单,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";
}
}
}