springboot下载文件

1.后端:
public void getExcelTemplate(HttpServletResponse response) throws UnsupportedEncodingException {

   //文件名最好不要用中文,会出现中文乱码
InputStream inputStream = new BufferedInputStream(this.getClass().getResourceAsStream("/template/template.xlsx"));

response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("模板.xlsx", "UTF-8"));

// 循环取出流中的数据
byte[] b = new byte[1024];
int len;
try {
while ((len = inputStream.read(b)) > 0)
response.getOutputStream().write(b, 0, len);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2.前端
可以直接使用window.location.href方式打开
downloadTemplate() {
window.location.href = "http://localhost:8080/getTemplate";
}
posted @ 2021-05-25 14:32  guohf  阅读(387)  评论(0编辑  收藏  举报