js vue react 文件下载

文章介绍了使用JavaScript在客户端处理普通文件、EXCEL和ZIP文件流下载的方法,包括利用`createElement`、`href`、`Blob`和`URL.createObjectURL`等技术来创建和触发下载链接。
摘要由CSDN通过智能技术生成
1. 普通文件下载
const a = document.createElement('a');
a.href = path;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
2. EXCEL 文件流下载
responseType: 'blob' // 表明返回服务器返回的数据类型
// 根据情况是否添加文件名称
// let filename = decodeURIComponent(res.headers.filename);
let result=res.data; 
//如果后端返回的result是进过Blob处理的,直接 window.URL.createObjectURL(result),如果没有,就需要先实例化new Blod处理之后再window.URL.createObjectURL(blob);

let blob = new Blob([result], {type: "application/vnd.ms-excel"});

let url = window.URL.createObjectURL(blob);
let link = document.createElement('a');
// link.download = filename;
link.href = url;
link.click();

3. ZIP 文件流下载

3.1  arraybuffer
responseType: "arraybuffer",  // 指定文件格式

const a = document.createElement("a");
a.href = (window.URL || window.webkitURL).createObjectURL(
new Blob([res], {
     type: 'application/octet-stream'
     })
);
const fileName = '***.zip'
a.download = decodeURIComponent(fileName);
a.dispatchEvent(new MouseEvent("click"));
3.2  blob
responseType: 'blob', // 指定格式

let blob = new Blob([res], { type: 'application/zip' });
let downloadElement = document.createElement('a');
let href = window.URL.createObjectURL(blob); //创建下载的链接
downloadElement.href = href;
downloadElement.download = ***.zip
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值