有时候我们会将一些静态模板文件,比如一些导入excel的模版放在resource目录下,那么我们springboot该如何实现resource目录下的文件下载功能呢?
这里我们现将一个名为xxx模板.xls的文件放在resource目录的下的template文件夹下,接下来我们写如下代码即可实现下下载功能:
@GetMapping("/download/template")
public void downloadTemplate(HttpServletRequest request, HttpServletResponse response){
String fileName = request.getParameter("fileName");
InputStream is = null;
OutputStream os = null;
try {
is = this.getClass().getClassLoader().getResourceAsStream("template"+ File.separator+fileName);
os = response.getOutputStream();
byte[] bytes = StreamUtils.copyToByteArray(is);
response.reset();
//下面这两行是为了解决跨域,如果没有跨域这两行可以删除
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.setContentType("application/octet-stream;charset=utf-8");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
response.addHeader("Content-Length", "" + bytes.length);
os.write(bytes);
os.flush();
}catch (Exception e) {
log.error("下载出错", e);
}finally {
try {
if(os != null) {
os.close();
}
if (is != null) {
is.close();
}
}catch (Exception e) {
log.error("关闭流出错", e);
}
}
}
接下来我们只需要发送类似:localhost:8080/api/download/template?fileName=xxx模板.xls
的get请求就可以触发该下载方法,从而现在springboot如何下载resource目录下的文件的下载了。