项目是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下找不到文件和文件名乱码)的更多相关文章

  1. SpringBoot项目里,让TKmybatis支持可以手写sql的Mapper.xml文件

    SpringBoot项目通常配合TKMybatis或MyBatis-Plus来做数据的持久化. 对于单表的增删改查,TKMybatis优雅简洁,无需像传统mybatis那样在mapper.xml文件里 ...

  2. vs 中明明包含了头文件所在路径,但是却找不到头文件

    vs基本不会出错,那么出错的只能是自己了. 哎,又被自己给蠢死了. 你可能在上面两个地方添加好了include 目录,但是却依然编译失败,失败的提示是找不到头文件所在路径,这是为什么呢. 很简单,因为 ...

  3. springboot项目获取resource下的文件

    package com.expr.exceldemo; import org.springframework.core.io.ClassPathResource; public class Test ...

  4. SpringBoot项目获取ApplicationContext来GetBean的方法

    一.简介 我们开发时,经常遇到有些实例需要动态创建,比如有构造函数的组件等.这时候,Spring时我们有ClassPathXmlApplicationContext,但是在Spring Boot时,我 ...

  5. 给你的SpringBoot项目定制一个牛年专属banner吧

    新春快乐,牛年大吉! 新的一年是牛年,在SpringBoot项目里自定义了一个牛年相关的banner,看起来可真不错. 上面是自己制作的一个banner,相关的ASCII字符在文末. SpringBo ...

  6. springboot-项目获取resources下文件的方法

    spring项目获取resources下文件的方法   最近写读取模板文件做一些后续的处理,将文件放在了项目的resources 下,发现了一个好用的读取方法:   比如上边是你需要读取的文件:  读 ...

  7. Springboot项目读取resource下的静态资源方法

    如果按相对路径直接读会定位到target下,因为springboot打包后读到这里 如果做单元测试的话是找不到文件的 File jsonFile = ResourceUtils.getFile(&qu ...

  8. Springboot项目与vue项目整合打包

    我的环境 * JDK 1.8 * maven 3.6.0 * node环境 1.为什么需要前后端项目开发时分离,部署时合并? 在一些公司,部署实施人员的技术无法和互联网公司的运维团队相比,由于各种不定 ...

  9. 使用docker运行springboot项目

    本文主要讲的是使用docker运行springboot项目 获取一个springboot项目 这里我没有重新构建,用的之前写的一个项目,直接从github上下载下来,地址:https://github ...

随机推荐

  1. 迁移虚拟机打开快照报错:CPUID错误

    场景:迁移虚拟机后,恢复快照报错 这个没办法解决,正常启动不会报错,恢复快照有可能报错,是因为你的cpu与快照那个cpu不匹配造成的

  2. 服务器 隐藏php版本,nginx版本号等

    隐藏php版本号: 打开php.ini配置文件  找到 expose_php 关键修改为 off 即可 重启后 web头部就不会有了 隐藏 nginx 服务器版本号: 打开nginx配置文件,在htt ...

  3. 三、vue之router

    三.vue之router 此时vue的脚手架.创建项目已经完成. ... vue的运行流程 index.html-->main.js-->App.vue-->router/index ...

  4. css背景图片充满DIV

    最近接手前端页面,让给调样式.哥纯粹一个代码程序猿,表示那些个样式应该让前端人员或者美工小妹妹来实现. 书归正传,碰到了问题,页面要在手机上展现,众所周知,手机在中国的牌子很多,很难做到统一. 页面上 ...

  5. 2018-2019-2 网络对抗技术 20165328 Exp2 后门原理与实践

    实验内容: 任务一:使用netcat获取主机操作Shell,cron启动任务二:使用socat获取主机操作Shell, 任务计划启动任务三:使用MSF meterpreter(或其他软件)生成可执行文 ...

  6. C# 操作docx文档

    一.需要引用DocX类库文件,可以直接在NuGet中找到. 二.创建文件,并添加一张表格 public static string fileName = AppDomain.CurrentDomain ...

  7. .net基础学java系列(一)视野

    本文目的在于扩展你我视野,求各位大神帮忙补充下表格中的内容,特别是Java的相关内容. 下面的文字纯是为了凑足150个字. 本人作为一名普通的.net程序员,也快混了十年了.在.net方面的知识面较广 ...

  8. Javascript数据结构与算法--队列(顺序队列、优先队列、循环队列)的实现与用法

    前言 队列和栈非常类似,前面已经讲过了栈的实现与用法,现在我们来说说队列. 队列介绍 队列遵循FIFO(First In First Out,先进先出)原则的一组有序的项. 队列是一种特殊的线性表,特 ...

  9. 将最小的OWIN身份验证添加到现有的ASP.NET MVC应用程序

    https://weblog.west-wind.com/posts/2015/Apr/29/Adding-minimal-OWIN-Identity-Authentication-to-an-Exi ...

  10. 关于spring aop Advisor排序问题

    关于spring aop Advisor排序问题 当我们使用多个Advisor的时候有时候需要排序,这时候可以用注解org.springframework.core.annotation.Order或 ...