<a href="xxx/xxx/xxx.html" download="xxx/xxx/newFile.pdf" />
最近有个需求, 要求h5 下载pdf 文件,并重命名文件进行保存, 后台提供pdf文件接口地址: https://xxx/xxx/xxxx.html 返回的是 Blob 类型文件数据。 前端接收到文件内容后下载保存在本地客户端, 通过 a download 属性实现方式:
onDownload(_url, newFileName) { // pdf 接口地址
$.ajax({
type: 'GET',
url: _url,
xhrFields: { responseType: "blob" },
success: function(res) {
try{
let url = URL.createObjectURL(res);
var a = document.createElement("a");
a.href = _url; // 给a标签赋上下载地址
a.download = newFileName;
a.style.display = "none"; // 让a标签不显示
document.body.appendChild(a);
a.click(); // a标签自点击
document.body.removeChild(a);
}
catch (e){
window.confirm("下载URL出错!");
}
}
});
}
通过 downdload 属性 可对下载文件进行重新命名,但是downdLoad 存在兼容性,当前值在chrome 浏览器能正常生效, 在IE浏览器中无法使用。 通过查找资料, 对于IE 的兼容性解决方式,写法:
onDownload(_url, newFileName) { // pdf 接口地址
$.ajax({
type: 'GET',
url: _url,
xhrFields: { responseType: "blob" },
success: function(res) {
try{
// IE 下载
if (navigator.msSaveBlob) {
window.navigator.msSaveBlob(res, newFileName);
return;
}
let url = URL.createObjectURL(res);
var a = document.createElement("a");
a.href = _url; // 给a标签赋上下载地址
a.download = newFileName;
a.style.display = "none"; // 让a标签不显示
document.body.appendChild(a);
a.click(); // a标签自点击
document.body.removeChild(a);
}
catch (e){
window.confirm("下载URL出错!");
}
}
});
}
通过添加IE 兼容性代码块, 成功在IE 中解决了现在问题。 但是,业务需要当前现在也要支持移动端浏览器, 例如: QQ浏览器, UC, 小米, 华为, 苹果safri 默认浏览器等。 通过测试发现: a download ,在这些移动端浏览器中,也存在兼容性问题, 不是下载无反应,就是能正常下载, 但是download 重命名的名称没生效。
对于移动端的处理方式是通过:
window.open(_url)
直接打开后台提供的文件下载接口, 不过这种方式就需要后端同学配合下, 通过在http 返回报文response-header
下添加 Content-Disposition:attachment;filename=%E7%90%86%E8%B4%A2%E4%BA%A7%E5%93%81%E7%A1%AE%E8%AE%A4%E5%8D%95.pdf
文件名内容描述。也就是当前文件重命名交给后端了, http截图:
这样就成功解决了移动端浏览器文件下载兼容性问题。