项目是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();
我使用的是第二种。
1 @PostMapping("/downloadTemplateFile")2 publicJSONData 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;8 try{9 File file =resource.getFile();10 if (!file.exists()) {11 return new JSONData(false,"模板文件不存在");12 }13 is = newFileInputStream(file);14 os =response.getOutputStream();15 bis = newBufferedInputStream(is);16 //设置响应头信息
17 response.setCharacterEncoding("UTF-8");18 this.response.setContentType("application/octet-stream; charset=UTF-8");19 StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");20 String fileName = new String(file.getName().getBytes(), "utf-8");21 contentDisposition.append(fileName).append("\"");22 this.response.set