SpringBoot下载文件
@GetMapping(value = "/downOrderTemplate") public ObjectRestResponse<String> downOrderTemplate() throws IOException { // String rootPath = System.getProperty("user.dir"); // log.info("======rootPath==="+rootPath); // File file = new File(rootPath.replace("\\","/")+"/src/main/resources/template/orderTemplate.xlsx"); ClassPathResource resource = new ClassPathResource("template/orderTemplate.xlsx"); InputStream inputStream = resource.getInputStream(); // File file = resource.getFile(); File file = new File("orderTemplate.xlsx"); try (FileOutputStream outputStream = new FileOutputStream(file)) { int read; byte[] bytes = new byte[1024]; while ((read = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, read); } } if(!file.exists()){ return new ObjectRestResponse<String>().rel(true).data("下载导入模板文件不存在"); } response.reset(); response.setContentType("application/octet-stream"); response.setCharacterEncoding("utf-8"); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment;filename=orderTemplate.xlsx"); try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) { byte[] buff = new byte[1024]; OutputStream os = response.getOutputStream(); int i = 0; while ((i = bis.read(buff)) != -1) { os.write(buff, 0, i); os.flush(); } } catch (IOException e) { log.error("{}",e); return new ObjectRestResponse<String>().rel(true).data("下载失败"); } return new ObjectRestResponse<String>().rel(true).data("下载成功"); }