Spring- 上传文件 MultipartFile.transferTo() 报错 FileNotFoundException

上传文件时,使用MultipartFile.transferTo()将文件保存到本地路径:

报错:

java.io.IOException: java.io.FileNotFoundException: C:\Users\XXXXX\AppData\Local\Temp\tomcat.8350081478984499756.8080\work\Tomcat\localhost\ROOT\app\file\xxxx.xlsx (系统找不到指定的路径。)

    @Override
    public String store(MultipartFile file, String fileName) throws IOException {

        String destPath "/app/file/";
        File filePath = new File(destPath);
        File dest = new File(filePath, fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("file save success");
        } catch (IOException e) {
            log.error("File upload Error: ", e);
            throw e;
        }
        return dest.getCanonicalPath();
    }

原因分析:

file.transferTo 方法调用时,判断如果是相对路径,则使用temp目录为父目录
因此保存在tomcat的临时work目录。

解决办法:

使用绝对路径:filePath.getAbsolutePath()

    @Override
    public String store(MultipartFile file, String fileName) throws IOException {

        String destPath "/app/file/";
        File filePath = new File(destPath);
        
        // 转为绝对路径
        File dest = new File(filePath.getAbsolutePath(), fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("file save success");
        } catch (IOException e) {
            log.error("File upload Error: ", e);
            throw e;
        }
        return dest.getCanonicalPath();
    }

补充:

也可以 file.getBytes() 获得字节数组,或file.getInputStream()进行流数据操作写进磁盘。

上传文件的访问

spring:
	resources:
    	static-locations: file:/app/file/  #访问系统外部资源,将该目录下的文件映射到系统下

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String absolutePath = new File("/app/file/").getAbsolutePath();
        
        registry.addResourceHandler("/upload/**") // 外部访问地址
                .addResourceLocations("file:" + absolutePath)// SpringBoot需要增加file协议前缀
                .setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// 设置浏览器缓存
    }
}

 

参考:https://www.programminghunter.com/article/8903728101/

你可能感兴趣的:(Java,Spring,Boot,spring,java,后端)