解决MultipartFile.transferTo(dest) 报FileNotFoundExcep的问题


Posted in Java/Android onJuly 01, 2021

Spring Upload file 报错FileNotFoundException

环境:

  • Springboot 2.0.4
  • JDK8
  • 内嵌 Apache Tomcat/8.5.32

表单,enctype 和 input 的type=file 即可,例子使用单文件上传

<form enctype="multipart/form-data" method="POST"
 action="/file/fileUpload">
 图片<input type="file" name="file" />
 <input type="submit" value="上传" />
</form>
@Controller
@RequestMapping("/file")
public class UploadFileController {
	@Value("${file.upload.path}")
	private String path = "upload/";

	@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
	@ResponseBody
	public String fileUpload(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return "false";
		}
		String fileName = file.getOriginalFilename();
		File dest = new File(path + "/" + fileName);
		if (!dest.getParentFile().exists()) { 
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest); // 保存文件
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}
	}
}

运行在保存文件 file.transferTo(dest) 报错

问题

dest 是相对路径,指向 upload/doc20170816162034_001.jpg

file.transferTo 方法调用时,判断如果是相对路径,则使用temp目录,为父目录

因此,实际保存位置为 C:\Users\xxxx\AppData\Local\Temp\tomcat.372873030384525225.8080\work\Tomcat\localhost\ROOT\upload\doc20170816162034_001.jpg

一则,位置不对,二则没有父目录存在,因此产生上述错误。

解决办法

transferTo 传入参数 定义为绝对路径

@Controller
@RequestMapping("/file")
public class UploadFileController {
	@Value("${file.upload.path}")
	private String path = "upload/";

	@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
	@ResponseBody
	public String fileUpload(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return "false";
		}
		String fileName = file.getOriginalFilename();
		File dest = new File(new File(path).getAbsolutePath()+ "/" + fileName);
		if (!dest.getParentFile().exists()) { 
			dest.getParentFile().mkdirs();
		}
		try {
			file.transferTo(dest); // 保存文件
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			return "false";
		}
	}
}

另外也可以 file.getBytes() 获得字节数组,OutputStream.write(byte[] bytes)自己写到输出流中。

补充方法

application.properties 中增加配置项

spring.servlet.multipart.location= # Intermediate location of uploaded files.

关于上传文件的访问

1、增加一个自定义的ResourceHandler把目录公布出去

// 写一个Java Config 
@Configuration
public class webMvcConfig implements org.springframework.web.servlet.config.annotation.WebMvcConfigurer{
	// 定义在application.properties
	@Value("${file.upload.path}")
	private String path = "upload/";
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		String p = new File(path).getAbsolutePath() + File.separator;//取得在服务器中的绝对路径
		System.out.println("Mapping /upload/** from " + p);
		registry.addResourceHandler("/upload/**") // 外部访问地址
			.addResourceLocations("file:" + p)// springboot需要增加file协议前缀
			.setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// 设置浏览器缓存30分钟
	}
}

application.properties 中 file.upload.path=upload/

实际存储目录

D:/upload/2019/03081625111.jpg

访问地址(假设应用发布在http://www.a.com/)

http://www.a.com/upload/2019/03081625111.jpg

2、在Controller中增加一个RequestMapping,把文件输出到输出流中

@RestController
@RequestMapping("/file")
public class UploadFileController {
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpServletResponse response;
	@Autowired
	protected ConversionService conversionService;

	@Value("${file.upload.path}")
	private String path = "upload/";	

	@RequestMapping(value="/view", method = RequestMethod.GET)
	public Object view(@RequestParam("id") Integer id){
		// 通常上传的文件会有一个数据表来存储,这里返回的id是记录id
		UploadFile file = conversionService.convert(id, UploadFile.class);// 这步也可以写在请求参数中
		if(file==null){
			throw new RuntimeException("没有文件");
		}
		
		File source= new File(new File(path).getAbsolutePath()+ "/" + file.getPath());
		response.setContentType(contentType);

		try {
			FileCopyUtils.copy(new FileInputStream(source), response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

MultipartFile.transferTo(dest) 报找不到文件

今天使用transferTo这个方法进行上传文件的使用发现了一些路径的一些问题,查找了一下记录问题所在

前端上传网页,使用的是单文件上传的方式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
    <form enctype="multipart/form-data" method="post" action="/upload">
        文件:<input type="file" name="head_img">
        姓名:<input type="text" name="name">
        <input type="submit" value="上传">
    </form>
</body>
</html>

后台网页

@Controller
@RequestMapping("/file")
public class UploadFileController {
    @Value("${file.upload.path}")
    private String path = "upload/";
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(path + "/" + fileName);
        if (!dest.getParentFile().exists()) { 
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }
}

这个确实存在一些问题

路径是不对的

dest 是相对路径,指向 upload/doc20170816162034_001.jpg

file.transferTo 方法调用时,判断如果是相对路径,则使用temp目录,为父目录

因此,实际保存位置为 C:\Users\xxxx\AppData\Local\Temp\tomcat.372873030384525225.8080\work\Tomcat\localhost\ROOT\upload\doc20170816162034_001.jpg

所以改为:

@Controller
@RequestMapping("/file")
public class UploadFileController {
    @Value("${file.upload.path}")
    private String path = "upload/";
    @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(new File(path).getAbsolutePath()+ "/" + fileName);
        if (!dest.getParentFile().exists()) { 
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Java/Android 相关文章推荐
图解排序算法之希尔排序Java实现
Jun 26 Java/Android
Java中使用Filter过滤器的方法
Jun 28 Java/Android
Springboot如何同时装配两个相同类型数据库
Nov 17 Java/Android
SpringDataJPA在Entity中常用的注解介绍
Dec 06 Java/Android
Java实现二分搜索树的示例代码
Mar 17 Java/Android
RestTemplate如何通过HTTP Basic Auth认证示例说明
Mar 17 Java/Android
Java的Object类的九种方法
Apr 13 Java/Android
Spring Boot 实现 WebSocket
Apr 30 Java/Android
Java死锁的排查
May 11 Java/Android
Android Canvas绘制文字横纵向对齐
Jun 05 Java/Android
Spring Cloud OAuth2实现自定义token返回格式
Jun 25 Java/Android
SpringBoot项目部署到阿里云服务器的实现步骤
Jun 28 Java/Android
Java中多线程下载图片并压缩能提高效率吗
分析ZooKeeper分布式锁的实现
Java并发编程必备之Future机制
详解Spring Boot使用系统参数表提升系统的灵活性
Jun 30 #Java/Android
浅谈resultMap的用法及关联结果集映射
Spring中bean的生命周期之getSingleton方法
每日六道java新手入门面试题,通往自由的道路
Jun 30 #Java/Android
You might like
PHP开发环境配置(MySQL数据库安装图文教程)
2010/04/28 PHP
php计算几分钟前、几小时前、几天前的几个函数、类分享
2014/04/09 PHP
PHP+MySQL修改记录的方法
2015/01/21 PHP
屏蔽PHP默认设置中的Notice警告的方法
2016/05/20 PHP
CI框架AR数据库操作常用函数总结
2016/11/21 PHP
PHP JWT初识及其简单示例
2018/10/10 PHP
JavaScript快速检测浏览器对CSS3特性的支持情况
2012/09/26 Javascript
jquery js 获取时间差、时间格式具体代码
2013/06/05 Javascript
让网页跳转到指定位置的jquery代码非书签
2013/09/06 Javascript
JQEasy-ui在IE9以下版本中二次加载的问题分析及处理方法
2014/06/23 Javascript
js实现hashtable的赋值、取值、遍历操作实例详解
2016/12/25 Javascript
谈谈Vue.js——vue-resource全攻略
2017/01/16 Javascript
微信小程序图片选择、上传到服务器、预览(PHP)实现实例
2017/05/11 Javascript
详解在vue-cli项目中安装node-sass
2017/06/21 Javascript
ES6数组与对象的解构赋值详解
2019/06/14 Javascript
详解小程序横屏方案对比
2020/06/28 Javascript
Python2.x版本中maketrans()方法的使用介绍
2015/05/19 Python
解决Python传递中文参数的问题
2015/08/04 Python
python代码实现ID3决策树算法
2017/12/20 Python
python 读取文本文件的行数据,文件.splitlines()的方法
2018/07/12 Python
Python爬虫之pandas基本安装与使用方法示例
2018/08/08 Python
Python批量生成特定尺寸图片及图画任意文字的实例
2019/01/30 Python
利用ImageAI库只需几行python代码实现目标检测
2019/08/09 Python
pytorch下的unsqueeze和squeeze的用法说明
2021/02/06 Python
CSS3只让背景图片旋转180度的实现示例
2021/03/09 HTML / CSS
科颜氏美国官网:Kiehl’s美国
2017/01/31 全球购物
C#里面可以避免一个类被其他类继承么?如何?
2013/09/26 面试题
行政前台岗位职责
2013/12/04 职场文书
高中班长自我鉴定
2013/12/20 职场文书
体育系毕业生求职自荐信
2014/04/16 职场文书
2014年图书室工作总结
2014/12/09 职场文书
2015年银行柜员工作总结报告
2015/04/01 职场文书
高效课堂教学反思
2016/02/24 职场文书
springcloud之Feign超时问题的解决
2021/06/24 Java/Android
SQL Server表分区降低运维和维护成本
2022/04/08 SQL Server
Mysql InnoDB 的内存逻辑架构
2022/05/06 MySQL