使用 Spring Boot 接收上传的文件,接收到的文件对象为srcFile,目标路径为 /upload/img/fileName.jpg,使用transferTo方法存储到本地:

File dstFile = new File("/upload/img/" + fileName);
srcFile.transferTo(dstFile);

提示目标文件路径不存在:

java.io.IOException: java.io.FileNotFoundException: C:\Users\syf\AppData\Local\Temp\tomcat.6910981657131718308.8080\work\Tomcat\localhost\ROOT\upload\img\5a6acf84e27448be9925959821ca1e90.png (系统找不到指定的路径。)

可以看见封装的transferTo方法自动把相对路径补全到了绝对路径,且是以 Tomcat 容器所在的临时目录为父目录补全的,而我们是想保存到项目的/upload/img/目录下。

解决方法:

不使用MultipartFile.transferTo,把 MultipartFile 对象转字节流后使用 FileOutputStream 手动保存二进制流:

// 这里的actualPath是相对项目根目录的路径
String actualPath = "src/main/webapp/upload/img/" + fileName;
String absolutePath = "/upload/img/" + fileName;

try {
    byte[] srcFileBytes = srcFile.getBytes();
    OutputStream f = new FileOutputStream(actualPath);
    f.write(srcFileBytes);
    f.close();
} catch (FileNotFoundException e) {
    System.out.println("File not found");
    System.out.println(actualPath);
    e.printStackTrace();
    return null;
} catch (IOException e) {
    e.printStackTrace();
    return null;
}
return absolutePath;

标签: java, springboot, spring

添加新评论