JavaScript tips —— 关于下载与导出的二三事
前言
- 获取文件流,编码后下载
- 获取文件的url,直接下载
浏览器的安全策略
预开新标签页
做法
- 在异步操作之前,先打开一个新标签页
- 请求后端资源的地址
- 获取url后去修改空白页的url
const downloadTab = window.open('about:blank');
ajax.get('xxx').then(url => {
// 使用后端资源的url进行下载
downloadTab.location.href = href;
}).catch(err => {
// 处理异常
downloadTab.close();
})
缺点
- 不管请求成功还是失败都会有新页面的闪烁出现
- 打开的新页面在什么时候关闭是个问题,因为如果请求时间过长,用户可能自己关闭新页面,更不好处理的情况是页面什么时候触发了下载,因为如果只是更改url就关闭窗口可能还没有开始下载的操作。
生成iframe
做法
ajax.get('xxx').then(href => {
if (!href) {
return;
}
if (!this.downIframe) {
this.downIframe = document.createElement('iframe'); // 动态创建iframe
this.downIframe.src = href; // iframe 中加载的页面
this.downIframe.id = 'downloadIframe'; // iframe 中加载的页面
this.downIframe.style.width = '1px';
this.downIframe.style.height = '1px';
this.downIframe.style.position = 'absolute';
this.downIframe.style.left = '-100px';
document.body.appendChild(this.downIframe); // 添加到当前窗体
} else {
this.downIframe.src = href; // iframe 中加载的页面
}
}).catch(err => {
// 处理异常
})
缺点
生成标签
ajax.get('xxx').then(href => {
if (!href) {
return;
}
var a = document.createElement('a');
var url = href;
var filename = 'test.zip';
a.href = url;
a.download = filename; // 在没有download属性的情况,target="_blank",仍会阻止打开
a.click();
}).catch(err => {
// 处理异常
})
处理文件流
function funDownload(content, filename) {
// 创建隐藏的可下载链接
var link = document.createElement('a');
link.download = filename;
link.style.display = 'none';
// 字符内容转变成blob地址
var blob = new Blob([content]);
//如果是excel格式
//var blob = new Blob([content], {type: 'application/vnd.ms-excel'}),
link.href = URL.createObjectURL(blob);
// 触发点击
document.body.appendChild(link);
link.click();
// 然后移除
document.body.removeChild(link);
};
createObjectURL() 方法时,都会创建一个新的 URL 对象,即使你已经用相同的对象作为参数创建过。当不再需要这些 URL 对象时,每个对象必须通过调用
URL.revokeObjectURL() 方法来释放。浏览器会在文档退出的时候自动释放它们,但是为了获得最佳性能和内存使用状况,你应该在安全的时机主动释放掉它们。
原文作者:nanchenk
本文来源: 掘金 如需转载请联系原作者
