今天写multipartFile转file,使用MultipartFile.transferTo(file)遇到了路径错误问题,代码如下:
/**
* multipartFile转file
* @param multipartFile
* @param tempPath
* @return File
*/
private static File getFile(MultipartFile multipartFile,String tempPath) {
String fileName = multipartFile.getOriginalFilename();
String filePath = tempPath;
File file = new File(filePath + fileName);
try {
multipartFile.transferTo(file);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
报错信息大致如下:
java.io.IOException: java.io.FileNotFoundException: /tmp/tomcat.8587388778869943211.8888/work/Tomcat/localhost/ROOT/temp/1.jpg.PNG (No such file or directory)
这很明显的路径不对,接着又扒multipartFile.transferTo源码,结果发现如下一段代码:
public void transferTo(File dest) throws IOException, IllegalStateException {
this.part.write(dest.getPath());
if (dest.isAbsolute() && !dest.exists()) {
FileCopyUtils.copy(this.part.getInputStream(), Files.newOutputStream(dest.toPath()));
}
}
它竟然判断了下是否是绝对路径.................
既然它要绝对路径,那我就给它绝对路径就好了,修改后的代码如下:
/**
* multipartFile转file
* @param multipartFile
* @param tempPath
* @return File
*/
private static File getFile(MultipartFile multipartFile,String tempPath) {
String fileName = multipartFile.getOriginalFilename();
String filePath = tempPath;
File file = new File(filePath + fileName);
try {
multipartFile.transferTo(file.getAbsoluteFile());
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
到这里就没啥问题了,真的是......唉,一入编程深似海....