springboot-项目获取resources下文件碰到的问题(classPath下找不到文件和文件名乱码)
项目是spring-boot + spring-cloud 并使用maven 管理依赖。在springboot+maven项目下怎么读取resources下的文件实现文件下载?
- 怎么获取resources目录下的文件?(相对路径)
方法一:
File sourceFile = ResourceUtils.getFile("classpath:templateFile/test.xlsx"); //这种方法在linux下无法工作
方法二:
Resource resource = new ClassPathResource("templateFile/test.xlsx"); File sourceFile = resource.getFile();
我使用的是第二种。
@PostMapping("/downloadTemplateFile")
public JSONData downloadTemplateFile(HttpServletResponse response) {
String filePath = "templateFile/test.xlsx";
Resource resource = new ClassPathResource(filePath);//用来读取resources下的文件
InputStream is = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
File file = resource.getFile();
if (!file.exists()) {
return new JSONData(false,"模板文件不存在");
}
is = new FileInputStream(file);
os = response.getOutputStream();
bis = new BufferedInputStream(is);
//设置响应头信息
response.setCharacterEncoding("UTF-8");
this.response.setContentType("application/octet-stream; charset=UTF-8");
StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
String fileName = new String(file.getName().getBytes(), "utf-8");
contentDisposition.append(fileName).append("\"");
this.response.setHeader("Content-disposition", contentDisposition.toString());
//边读边写
byte[] buffer = new byte[500];
int i;
while ((i = bis.read(buffer)) != -1) {
os.write(buffer, 0, i);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
return new JSONData(false,"模板文件不存在");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null) os.close();
if(bis != null) bis.close();
if(is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new JSONData("模板文件下载成功");
}
高高兴兴的启动项目后发现还是找不到文件,错误日志:
java.io.FileNotFoundException: class path resource [templateFile/test.xlsx] cannot be resolved to URL because it does not exist
at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:195)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:129)
at com.citycloud.parking.support.controller.operate.OperateBusinessUserController.downloadTemplateFile(OperateBusinessUserController.java:215)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:158)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:126)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:111)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
因为我知道Resource resource = new ClassPathResource("templateFile/test.xlsx");就是到classPath*(注意这里有个*)下去找,然后就去项目本地的目录下找classPath下是否有这个文件(maven的classPath在 “target\classes”目录下),就发现并没有这个文件在。
后面仔细想想这是Maven项目啊,所以就找pom.xml文件去看看,突然想起:springboot的maven默认只会加载classPath同级目录下文件(配置那些),其他的需要配置<resources>标签:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<!--是否替换资源中的属性-->
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
<include>**/Dockerfile</include>
<include>**/*.xlsx</include>
</includes>
<!--是否替换资源中的属性-->
<filtering>false</filtering>
</resource>
</resources>
</build>
重新启动,再到classPath下看,发现有了这个文件了,同时也能获取了。如果文件名为中文的话就会出现乱码的情况。
- 怎么解决文件名中文乱码?
Access-Control-Allow-Origin →*
Access-Control-Allow-Credentials →true
Access-Control-Allow-Headers →accessToken,Access-Control-Allow-Origin,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers
Access-Control-Allow-Methods →POST,GET,PUT,PATCH,DELETE,OPTIONS,HEAD
Access-Control-Max-Age →360
Content-disposition →attachment; filename="????????-??????????.xlsx"
Content-Type →application/octet-stream;charset=UTF-8
Transfer-Encoding →chunked
Date →Fri, 19 Apr 2019 06:47:34 GMT
上面是使用postman测试中文乱码response响应头相关信息。
后面怎么改都乱码,然后我就试着到浏览器中请求试试,结果发现只是postman的原因,只要文件名编码跟返回内容编码一致("Content-disposition"和“ContentType”)就行:
this.response.setContentType("application/octet-stream; charset=iso-8859-1");
StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
String fileName = file.getName();
contentDisposition.append(fileName).append("\"");
//设置文件名编码
String contentDispositionStr = new String(contentDisposition.toString().getBytes(), "iso-8859-1");
this.response.setHeader("Content-disposition", contentDispositionStr);
到此全部结束!
springboot-项目获取resources下文件碰到的问题(classPath下找不到文件和文件名乱码)的更多相关文章
- SpringBoot项目里,让TKmybatis支持可以手写sql的Mapper.xml文件
SpringBoot项目通常配合TKMybatis或MyBatis-Plus来做数据的持久化. 对于单表的增删改查,TKMybatis优雅简洁,无需像传统mybatis那样在mapper.xml文件里 ...
- vs 中明明包含了头文件所在路径,但是却找不到头文件
vs基本不会出错,那么出错的只能是自己了. 哎,又被自己给蠢死了. 你可能在上面两个地方添加好了include 目录,但是却依然编译失败,失败的提示是找不到头文件所在路径,这是为什么呢. 很简单,因为 ...
- springboot项目获取resource下的文件
package com.expr.exceldemo; import org.springframework.core.io.ClassPathResource; public class Test ...
- SpringBoot项目获取ApplicationContext来GetBean的方法
一.简介 我们开发时,经常遇到有些实例需要动态创建,比如有构造函数的组件等.这时候,Spring时我们有ClassPathXmlApplicationContext,但是在Spring Boot时,我 ...
- 给你的SpringBoot项目定制一个牛年专属banner吧
新春快乐,牛年大吉! 新的一年是牛年,在SpringBoot项目里自定义了一个牛年相关的banner,看起来可真不错. 上面是自己制作的一个banner,相关的ASCII字符在文末. SpringBo ...
- springboot-项目获取resources下文件的方法
spring项目获取resources下文件的方法 最近写读取模板文件做一些后续的处理,将文件放在了项目的resources 下,发现了一个好用的读取方法: 比如上边是你需要读取的文件: 读 ...
- Springboot项目读取resource下的静态资源方法
如果按相对路径直接读会定位到target下,因为springboot打包后读到这里 如果做单元测试的话是找不到文件的 File jsonFile = ResourceUtils.getFile(&qu ...
- Springboot项目与vue项目整合打包
我的环境 * JDK 1.8 * maven 3.6.0 * node环境 1.为什么需要前后端项目开发时分离,部署时合并? 在一些公司,部署实施人员的技术无法和互联网公司的运维团队相比,由于各种不定 ...
- 使用docker运行springboot项目
本文主要讲的是使用docker运行springboot项目 获取一个springboot项目 这里我没有重新构建,用的之前写的一个项目,直接从github上下载下来,地址:https://github ...
随机推荐
- 2019年最受欢迎IMX6系列开发板,资料全开源,助力产品研发不在话下
迅为IMX6开发板: Android4.4系统 Linux + Qt5.7系统 Ubuntu12.04系统 部分真实案例:HMI:3D打印机:医疗设备:工控机:触控一体机:车载终端 板载:4G全网 ...
- Stm32之通用定时器复习
因为毕业设计要用到PWM调光很久都没用到Stm32的定时器,有些内容已经遗忘,为了回顾复习相关内容今天开下通用定时器这一章节的数据手册. 1.时钟 通用定时器一般是TIM2~TIM5,TIM1.TIM ...
- [系统集成] 基于 elasticsearch 的企业监控方案
注: 2017年10月16日: 使用中发现 es 查询时序数据的性能较差,且 watch 脚本的编写比较麻烦,因此已将监控系统切换到了 influxdb+grafana平台.新监控系统各方面情况比较满 ...
- redhat7初始化yum源
1.卸载原有的yum [app@localhost ~]$ su - root Password: Last :: CST on pts/ [root@localhost ~]# cd /etc/yu ...
- TCP-IP详解笔记8
TCP-IP详解笔记8 TCP超时与重传 下层网络层(IP)可能出现丢失, 重复或丢失包的情况, TCP协议提供了可靠的数据传输服务. TCP启动重传操作, 重传尚未确定的数据. 基于时间重传. 基于 ...
- 29 内置方法 eval | exec 元类 单例
eval与exec内置方法 将字符串作为执行目标,得到响应结果 eval常用作类型转换:该函数执行完有返回值 exec拥有执行更复杂的字符串:可以形成名称空间 eval内置函数的使用场景: 1.执 ...
- 单点登录前戏(未使用jwt版本)
建表 from django.db import models import jwt # Create your models here. # 角色表 class RoleTable(models.M ...
- CentOS7没有eth0网卡
本人刚刚进去运维圈,写写博客,记录一下自己日常工作学习中的各种问题,方便自己,方便他人. CentOS7系统安装完毕之后,输入ifconfig命令发现没有eth0,不符合我们的习惯.而且也无法远程ss ...
- PHP字符过滤方法
function str_filter_replace($str) { if (empty($str)) return false; $str = htmlspecialchars($str); $s ...
- HTML5原生拖拽/拖放(drag & drop)详解
前言 拖放(drap && drop)在我们平时的工作中,经常遇到.它表示:抓取对象以后拖放到另一个位置.目前,它是HTML5标准的一部分.我从几个方面学习并实践这个功能. 拖放的流程 ...