spring boot中jar包方式的下载本地静态文件,下面代码说话,非常实用,避免误区:
try {
// 以流的形式下载文件这种方法,打成jar包之后,下载的文件,会被损坏
InputStream fis =this.getClass().getClassLoader().getResourceAsStream("/templates/imports/XXXX.docx");
response.setHeader("Content-Disposition", "attachment;filename=XXX.docx");
response.setContentType("application/msword;charset=UTF-8");
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.flush();
fis.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
以上代码能解决打成jar包后下载本地静态文件的问题.