vue element 调用后台下载文件

这篇博客详细记录了如何使用VueElement组件调用后台接口实现文件下载。前端通过创建Blob对象和模拟点击下载链接的方式,后台设置相应响应头并读取文件流输出。关键步骤包括设置Content-Type,Content-Disposition以及利用HttpServletResponse进行文件流传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值