vue element 调用后台下载文件
调用后台下载文件,简单记录一下
前端代码
代码中的 res为后台返回的文件流
let blob = new Blob([res], { type: "application/vnd.ms-excel" });
let elink = document.createElement('a');
elink.download = '下载文件名称.xlsx'
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL对象
document.body.removeChild(elink);
后台代码
public void download(HttpServletResponse response) {
// 获取文件路径
String path = this.getClass().getClassLoader().getResource("file").getPath();
File file = new File(path + File.separator + "下载文件名称.xlsx");
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
try (FileInputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream();){
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8") + "");
IOUtils.copy(in, out);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
logger.info("文件下载失败,原因{}", e);
}
}
参考博客
https://blog.csdn.net/m0_56896206/article/details/118796542