一、下面这种方法在本地是可以成功下载的,但是springboot打成jar包,部署到服务器就不行了,具体原因看另一篇文章:
SpringBoot项目打包成jar后读取文件的大坑
1.控制器
@ApiOperation(value = "下载导入模板")
@GetMapping("download1")
public void download1(HttpServletResponse response) throws Exception {
File tem = ResourceUtils.getFile("classpath:excelTpl/carCardTemplate.xlsx");
MyUtil.download(tem, "月租车信息导入模板", response);
}
2.下载工具方法
public static void download(File localFile,String downName, HttpServletResponse res) throws IOException {
String subffix = localFile.getName().substring(localFile.getName().lastIndexOf("."));
// 设置信息给客户端不解析
String type = new MimetypesFileTypeMap().getContentType(localFile.getName());
// 设置contenttype,即告诉客户端所发送的数据属于什么类型
res.setHeader("Content-type",type);
// 设置编码
String name = new String(downName.concat(subffix).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
// 设置扩展头,当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
res.setHeader("Content-Disposition", "attachment;filename=" + name);
// 发送给客户端的数据
OutputStream outputStream = res.getOutputStream();
// byte[] buff = new byte[1024];
// BufferedInputStream bis = null;
// 读取filename
// bis = new BufferedInputStream(new FileInputStream(fileTem));
// int read = 0;
// while ((read = bis.read(buff)) != -1) {
// outputStream.write(buff, 0, read);
// outputStream.flush();
// }
byte[] readByte = Files.readAllBytes(localFile.toPath());
outputStream.write(readByte);
outputStream.flush();
outputStream.close();
}
二、下面这种方法是通用方法
1.控制器
@ApiOperation(value = "下载导入模板")
@GetMapping("download")
public void download1(HttpServletResponse response) throws Exception {
InputStream in = this.getClass().getResourceAsStream("/excelTpl/carCardimportTemp.xlsx");
MyUtil.download(in, "月租车信息导入模板", response);
}
2.工具方法
public static void download(InputStream in, String downName, HttpServletResponse res) throws IOException {
res.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
res.setCharacterEncoding("UTF-8");
String fileName = URLEncoder.encode(downName, "UTF-8").replaceAll("\+", "%20");
String name = new String(fileName.concat(".xlsx").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
res.setHeader("Content-Disposition", "attachment;filename=" + name);
OutputStream outputStream = res.getOutputStream();
// byte[] buff = new byte[1024];
// BufferedInputStream bis = null;
// 读取filename
// bis = new BufferedInputStream(in);
// int read = 0;
// while ((read = bis.read(buff)) != -1) {
// outputStream.write(buff, 0, read);
// outputStream.flush();
// }
StreamUtils.copy(in,outputStream);
outputStream.close();
}



