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/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值