MultipartFile.transferTo(dest) 报 FileNotFoundException
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)@ResponseBodypublic 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)@ResponseBodypublic 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.
关于上传文件的访问
增加一个自定义的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
在Controller中增加一个RequestMapping,把文件输出到输出流中
@RestController
@RequestMapping("/file")
public class UploadFileController {@Autowiredprotected HttpServletRequest request;@Autowiredprotected HttpServletResponse response;@Autowiredprotected ConversionService conversionService;@Value("${file.upload.path}")private String path = "upload/"; @RequestMapping(value="/view", method = RequestMethod.GET)public Object view(@RequestParam("id") Integer id){// 通常上传的文件会有一个数据表来存储,这里返回的id是记录idUploadFile 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) 报 FileNotFoundException相关推荐
- MultipartFile.transferTo(dest) 报找不到文件错误以及解决方法
MultipartFile.transferTo(dest) 报找不到文件 今天使用transferTo这个方法进行上传文件的使用发现了一些路径的一些问题,查找了一下记录问题所在 前端上传网页,使用的 ...
- transferto 文件不存在_文件上传时,MultipartFile.transferTo() 方法报 FileNotFoundException...
Spring Upload File 报错FileNotFoundException 环境: Springboot2.0.4JDK1.8内嵌 Apache Tomcat/8.5.32 1.前端代码 前 ...
- MultipartFile.transferTo()用法
环境: Springboot 2.0.4 JDK8 表单,enctype 和 input 的type=file 即可,例子使用单文件上传 <form enctype="multipar ...
- SpringBoot用MultipartFile.transferTo传递相对路径的问题
起因: 工作中简单的图片不需要使用第三方文件存储服务,上传到项目所在路径保存,在使用 MultipartFile.transferTo 转存文件时报错,路径找不到. 原因: 当MultipartFil ...
- 【报错记录】SpringBoot中MultipartFile上传报/tmp/tomcat.***.tmp (No such file or directory)
前言 我这个接口的需求大概是用户上传一个Excel文件到后端,后端解析这个Excel,并做一系列很耗时的操作.由于这个接口很耗时,因此做成了异步处理的方式,将处理完成的信息通过消息中心告诉用户,并不是 ...
- transferto方法的应用_Java MultipartFile.transferTo方法代碼示例
本文整理匯總了Java中org.springframework.web.multipart.MultipartFile.transferTo方法的典型用法代碼示例.如果您正苦於以下問題:Java Mu ...
- springboot上传文件MultipartFile.transferTo()
根据springMvc教程,改写的springboot文件上传功能,实际上很简单,核心使用的是MultipartFile类: org.springframework.web.multipart.Mul ...
- Elasticsearch启动报FileNotFoundException: search_slowlog.json (Permission denied),带详细解决方法
[现象] 2021-07-06 11:54:25,559 main ERROR RollingFileManager (/opt/apps/es/elasticsearch/logs/elastics ...
- MultipartFile的transferTo方法注意事项
前言 最近用SpringBoot写文件上传功能,使用参数绑定之后确实是非常的方便了.但是,项目部署就出现了问题,搞得我一脸懵逼.后来,才发现是因为我使用了相对路径导致的,这个绝对是一个坑人的地方,不过 ...
最新文章
- Redis以及Redis的php扩展安装无错版
- php 获取js变量
- es6 --- 使用proxy对数据进行劫持
- PostgreSQL and SQLAlchemy [ubuntu]
- mysql bin 分析_mysql bin log 分析
- canvas width/height和style.width/style.height
- linux sata 3驱动下载,linux – SSD SATA3驱动器可能存在的问题
- 句法分析——CYK分析算法
- springboot集成阿里云短信
- Chrome配置Proxy代理
- 骨传导耳机工作原理,骨传导耳机优缺点
- 来自春天的仪式感:英伦花艺佳作,用鲜花点缀生活丨好书优选
- java 实例化异常_如何处理实例化类对象时发生的异常
- es高级客户端聚合查询api快速入门
- VBS识别网页验证码
- 必须掌握的八个dos命令
- 魔域手游登录不显示服务器失败,魔域手游怎么找回之前登录的区 | 手游网游页游攻略大全...
- 基于PaddleHub的虚拟粉圈微博生成
- 2022-08-29 AndroidR 修改默认usb连接模式为MTP(Media Transfer Protocol)),UsbDeviceManager.java里面处理OTG口usb设备拔插侦听
- 视觉SLAM-手写VIO三角测量代码注释
热门文章
- Python实验报告五 python基础试题练习
- FLOTHERM 热分析仿真 风冷 水冷 自冷视频教程
- 万全r680g7配置raid_联想万全R680G7服务器安装部署Vmware虚拟化系统说明书模板
- spark报Got an error when resolving hostNames. Falling back to /default-rack for all
- sklearn中的学习曲线learning_curve函数
- VML,The Vector Markup Language(矢量可标记语言)
- IATF16949标准的五大工具
- cr2 android,CR2 文件扩展名: 它是什么以及如何打开它?
- 19、猿人学第四题:雪碧图、样式干扰【Post/Js逆向笔记】
- 秋季是掉头发的季节,怎么做才能少掉点