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

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";
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 文件上传SpringBoot后端MultipartFile参数报空问题的解决办法

    最近写了一个文件上传的小demo,就是简单的前端html页面,后端controller接收,但是后端一直报错文件为null,看了很多文章,有说spring-boot自带的org.springframework.web.multipart.MultipartFile和Multipart冲突了,要在启动类中加入@EnableAutoConfiguration(exclue={MultipartAutoConfiguration.class}),有说要在MultipartFile参数前加上@Reque

  • 文件路径正确,报java.io.FileNotFoundException异常的原因及解决办法

    新添加个发文类型 insert into mis.zyb_sf_type values('121','榆财法字','榆财法字',2,'0','1',21,NULL,'0','发文模板.doc','') 创建文章时出错了, 异常信息: 文件保存失败 Java.io.FileNotFoundException: E:\tomcat\jinzhongshi\jinzs_yuci\webapps\myDoJZS\word\template_fw\发文模版.doc (系统找不到指定的文件.) at jav

  • 解决springboot MultipartFile文件上传遇到的问题

    1.ajax传过去的参数在controller接受不到 解决:在contoller中增加@RequestParam 例如:saveUploadFile( @RequestParam("file") MultipartFile file,HttpServletRequest request) 2.org.springframework.web.multipart.support.MissingServletRequestPartException: Required request pa

  • SpringMVC使用MultipartFile 实现异步上传方法介绍

    目的是实现异步上传 1.添加pom依赖 添加pom依赖,因为用的ajax,数据需要转成json的格式进行传输,所以还有加入一个JSON jar包: <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>

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

    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"> 图片<

  • 快速解决百度编译器json报错的问题

    在MyEclipse中JSON字符串的换行值是不同的,必须以'/n'换行,如果只是json验证的问题,可以把json的验证关掉试试. 点击所在的项目->Project->Proterties->MyEclipse->Validation,把JSON Validator中的Manual和Build的对号给去掉,然后apply,确定,clean缓存. 清除myeclipse缓存的方法如下 找到软件导航窗内的project下的clean,选择要清除缓存的项目,点击clean projec

  • 解决laravel 5.1报错:No supported encrypter found的办法

    本文主要介绍了关于解决laravel 5.1报错:No supported encrypter found的办法,分享出来供大家参考学习,下面来看看详细的介绍: 问题描述 在使用laravel5.1进行项目开发的时候,出现了"No supported encrypter found. The cipher and / or key length are invalid."的报错信息,导致页面无法显示. 网上的绝大多数答案都是直接执行PHP artisan key:generate即可.

  • 解决Layui中layer报错的问题

    问题描述: Uncaught ReferenceError: layer is not defined 解决方法,查看网上说名,是非独立版导致直接使用layer导致,只需要在使用时加一说明,申明一下使用. layui.use(['element','layer'], function(){ var element = layui.element,layer=layui.layer; //一些事件监听 element.on('nav(topBarNav)', function(data){ con

  • vue 解决循环引用组件报错的问题

    做项目时遇到使用循环组件,因为模式一样,只有数据不一样.但是按照普通的组件调用格式来做时报错,错误信息为Unknown custom element: <pop> - did you register the component correctly? For recursive components, make sure to provide the "name" option. 查询了官方文档,还有其他的资料,发现是循环调用组件时,组件比vue实例后创建,官方文档里写组件

  • 解决pip install xxx报错SyntaxError: invalid syntax的问题

    python--pip install xxx报错SyntaxError: invalid syntax 在安装好python后,进入python运行环境后,因为我要用pip安装开发Web App需要的第三方库,执行pip install aiohttp,发现会报错SyntaxError: invalid syntax,刚开始以为是拼写或者空格问题或者python版本问题,结果用pip3还是一样的. 然后百度了一下,发现原来用pip安装时都要在cmd命令行里启动的,而在python中无法运行.退

  • vue如何解决循环引用组件报错的问题

    问题由来 最近在做项目的时候遇到使用循环组件,因为模式一样,只有数据不一样.按照普通组件调用格式来做的时候总是报错,错误信息为[Vue warn]: Unknown custom element: <selfile> - did you register the component correctly? For recursive components, make sure to provide the "name" option. 解决方案 查询了网上各种资料之后,发现是

  • Python 解决OPEN读文件报错 ,路径以及r的问题

    Python 中 'unicodeescape' codec can't decode bytes in position XXX: trun错误解决方案 背景描述 今天在运用Python pillow模块处理图片时遇到一个错误 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape 刚开始以为是图片名字有中文,不识别,于是

  • 解决TensorFlow模型恢复报错的问题

    错误信息 Attempting to use uninitialized value input_producer/input_producer/limit_epochs/epochs 今天在模型恢复的时候出现上图报错信息,最后发现是由于调用tf.train.slice_input_producer方法产生的错误信息.它本身认为是一个tensor 修改方法: 获取batch后,在sess中先初始化即可 sess.run(tf.global_variables_initializer()) ses

  • 解决Intellij IDEA运行报Command line is too long的问题

    报错信息大概如下: Error running 'xxx': Command line is too long. Shorten command line for xxx or also for Application default configuration. 解决方案(1): 找到项目下的.idea/workspace.xml,在标签<component name="PropertiesComponent">里添加一行属性:<property name=&quo

随机推荐