Posted in Javascript onSeptember 25, 2019
本文实例为大家分享了Vue利用Blob下载原生二进制数组文件的具体代码,供大家参考,具体内容如下
在服务端推送过来的二进制数组(JSON格式),在前端要处理成JS原生数组以后才能做成Blob,有两个地方要注意(详细注释),代码如下:
Vue.prototype.$downloadFile = (filename, data) => { if (!data) return; let arr8 = Uint8Array.from(data); //!!!注意1:应根据数据的类型选择适当的JS原生数组类型进行转换,也就是说服务端推送的byte型数组还是int型数组等。 //定义文件内容,类型必须为Blob 否则createObjectURL会报错 let blob = null; let type = 'application/octet-binary'; if (typeof (window.Blob) == "function") { blob = new Blob([arr8], {//!!!注意2:数组两边必须加上[] type: type }); } else { let BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder; let bb = new BlobBuilder(); bb.append([arr8]); blob = bb.getBlob(type); } let URL = window.URL || window.webkitURL; let bloburl = URL.createObjectURL(blob); let anchor = document.createElement("a"); if ('download' in anchor) { anchor.style.visibility = "hidden"; anchor.href = bloburl; anchor.download = filename; document.body.appendChild(anchor); let evt = document.createEvent("MouseEvents"); evt.initEvent("click", true, true); anchor.dispatchEvent(evt); document.body.removeChild(anchor); } else if (navigator.msSaveBlob) { navigator.msSaveBlob(blob, filename); } else { location.href = bloburl; } //移除链接释放资源 };
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。
Vue利用Blob下载原生二进制数组文件
- Author -
yycdtu声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@