springboot-项⽬获取resources下⽂件碰到的问题(classPath下不。
。。
项⽬是spring-boot + spring-cloud 并使⽤maven 管理依赖。在springboot+maven项⽬下怎么读取resources下的⽂件实现⽂件下载?
怎么获取resources⽬录下的⽂件?(相对路径)
⽅法⼀:
File sourceFile = File("classpath:templateFile/test.xlsx"); //这种⽅法在linux下⽆法⼯作
⽅法⼆:
Resource resource = new ClassPathResource("templateFile/test.xlsx"); File sourceFile = File();
我使⽤的是第⼆种。
1  @PostMapping("/downloadTemplateFile")
2public JSONData downloadTemplateFile(HttpServletResponse response) {
3        String filePath = "templateFile/test.xlsx";
4        Resource resource = new ClassPathResource(filePath);//⽤来读取resources下的⽂件
5        InputStream is = null;
6        BufferedInputStream bis = null;
7        OutputStream os = null;
8try {
9            File file = File();
10if (!ists()) {
11return new JSONData(false,"模板⽂件不存在");
12            }
13            is = new FileInputStream(file);
14            os = OutputStream();
15            bis = new BufferedInputStream(is);
16//设置响应头信息
17            response.setCharacterEncoding("UTF-8");
19            StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
20            String fileName = new Name().getBytes(), "utf-8");
21            contentDisposition.append(fileName).append("\"");
23//边读边写
24byte[] buffer = new byte[500];
25int i;
26while ((i = ad(buffer)) != -1) {
27                os.write(buffer, 0, i);
28            }
29            os.flush();
30        } catch (FileNotFoundException e) {
31            e.printStackTrace();
32return new JSONData(false,"模板⽂件不存在");
33        } catch (IOException e) {
34            e.printStackTrace();
35        } finally {
36try {
37if(os != null) os.close();
38if(bis != null) bis.close();
39if(is != null) is.close();
40            } catch (IOException e) {
41                e.printStackTrace();
42            }
43        }
44return new JSONData("模板⽂件下载成功");
45    }
⾼⾼兴兴的启动项⽬后发现还是不到⽂件,错误⽇志:
1 java.io.FileNotFoundException: class path resource [templateFile/test.xlsx] cannot be resolved to URL because it does not exist
2    at URL(ClassPathResource.java:195)
3    at File(AbstractFileResolvingResource.java:129)
4    at com.citycloud.ller.operate.OperateBusinessUserController.downloadTemplateFile(OperateBusinessUserController.java:215)
5    flect.NativeMethodAccessorImpl.invoke0(Native Method)
6    flect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
7    flect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
8    at flect.Method.invoke(Method.java:498)
9    at org.hod.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
10    at org.hod.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
11    at org.springframework.web.hod.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
12    at org.springframework.web.hod.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
13    at org.springframework.web.hod.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
14    at org.springframework.web.hod.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
15    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
16    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
17    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
18    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:877)
19    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
20    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
21    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
22    at org.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
23    at org.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
24    at at.websocket.server.WsFilter.doFilter(WsFilter.java:52)
25    at org.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
26    at org.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
27    at org.springframework.ics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:158)
28    at org.springframework.ics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:126)
29    at org.springframework.ics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:111)
30    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
31    at org.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
因为我知道Resource resource = new ClassPathResource("templateFile/test.xlsx");就是到classPath*(注意这⾥有个*)下去,然后就去项⽬本地的⽬录下classPath下是否有这个⽂件(maven的classPath在 “target\classes”⽬录下),就发现并没有这个⽂件在。
后⾯仔细想想这是Maven项⽬啊,所以就l⽂件去看看,突然想起:springboot的maven默认只会加载classPath同级⽬录下⽂件(配置那些),其他的需要配置<resources>标签:
1 <build>
2  <resources>
3      <resource>
4        <directory>src/main/java</directory>
5        <includes>
6          <include>**/*.properties</include>
7          <include>**/*.xml</include>
8        </includes>
9        <!--是否替换资源中的属性-->
10        <filtering>false</filtering>
11      </resource>
12      <resource>
13        <directory>src/main/resources</directory>
14        <includes>
15          <include>**/*.properties</include>
16          <include>**/*.xml</include>
17          <include>**/*.yml</include>
18          <include>**/Dockerfile</include>
19<include>**/*.xlsx</include>
20        </includes>
21        <!--是否替换资源中的属性-->
22        <filtering>false</filtering>
23      </resource>
24  </resources>
25</build>
重新启动,再到classPath下看,发现有了这个⽂件了,同时也能获取了。如果⽂件名为中⽂的话就会出现乱码的情况。
怎么解决⽂件名中⽂乱码?
1 Access-Control-Allow-Origin →*
2 Access-Control-Allow-Credentials →true
3 Access-Control-Allow-Headers →accessToken,Access-Control-Allow-Origin,Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers
4 Access-Control-Allow-Methods →POST,GET,PUT,PATCH,DELETE,OPTIONS,HEAD
5 Access-Control-Max-Age →360
6 Content-disposition →attachment; filename="-??.xlsx"
7 Content-Type →application/octet-stream;charset=UTF-8
springcloud和springboot8 Transfer-Encoding →chunked
9 Date →Fri, 19 Apr 2019 06:47:34 GMT
上⾯是使⽤postman测试中⽂乱码response响应头相关信息。
后⾯怎么改都乱码,然后我就试着到浏览器中请求试试,结果发现只是postman的原因,只要⽂件名编码跟返回内容编码⼀致("Content-disposition"和“ContentType”)就⾏:
2 StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
3 String fileName = Name();
4 contentDisposition.append(fileName).append("\"");
5//设置⽂件名编码
6 String contentDispositionStr = new String().getBytes(), "iso-8859-1");
到此全部结束!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。