上传报错信息
Springboot 上传文件报错,在使用 MultipartFile 的 transferTo 方法时报错,代码如下:
public String tmpMdbFile(MultipartFile file) {
File dest = new File(TMP_DIR + System.currentTimeMillis() + "_" + file.getOriginalFilename());
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
return dest.getAbsolutePath();
}
报错信息如下:
java.io.IOException: java.io.FileNotFoundException: C:\Users\yawn\AppData\Local\Temp\tomcat.5222418755956874474.8095\work\Tomcat\localhost\ROOT\tmp\xxx (No such file or directory) 或
java.io.IOException: java.io.FileNotFoundException: C:\Users\yawn\AppData\Local\Temp\tomcat.5222418755956874474.8095\work\Tomcat\localhost\ROOT\tmp\xxx (系统找不到指定的路径。)
解决方法
原因是我们使用了相对路径,MultipartFile 在使用transferTo的路径就会出现问题。解决办法如下:
1 解决这个问题可以使用绝对路径。即代码中的常量 TMP_DIR 设置为绝对路经。
2 或者不使用transferTo方法,而从multipartFile的输入流读取文件内容。代码如下:
public String tmpMdbFile(InputStream is, String fileName) {
File dest = new File(TMP_DIR + System.currentTimeMillis() + "_" + fileName);
saveFile(is, dest);
return dest.getAbsolutePath();
}
private void saveFile(InputStream is, File dest) {
try(FileOutputStream fos = new FileOutputStream(dest)) {
int len;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
}