栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

报错:

java.io.IOException: java.io.FileNotFoundException: C:UsersXXXXXAppDataLocalTemptomcat.8350081478984499756.8080workTomcatlocalhostROOTappfilexxxx.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/

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/672497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号