blob对象

摘要:JS blob对象的一些用法示例,主要是下载

Page Demo

<html>
 <head></head>
 <body>
  <div id="forAppend" class="demo"></div> 
  <script>
var eleAppend = document.getElementById("forAppend");
window.URL = window.URL || window.webkitURL;
if (typeof history.pushState == "function") {
    var xhr = new XMLHttpRequest();
    xhr.open("get", "test.png", true);
    xhr.responseType = "blob";
    xhr.onload = function() {

        if (this.status == 200) {
            var blob = this.response;

            console.log(blob);
            openDownloadDialog(blob,'1231232');
            // var img = document.createElement("img");
            // img.onload = function(e) {
            //     window.URL.revokeObjectURL(img.src); // 清除释放  
            // };
            // img.src = window.URL.createObjectURL(blob);
            // eleAppend.appendChild(img);
        }
    }

    xhr.send();
} else {
    eleAppend.innerHTML = '<p style="color:#cd0000;">浏览器不给力,请更换浏览器后重试</p>';
}
/**
 * 通用的打开下载对话框方法,没有测试过具体兼容性
 * @param url 下载地址,也可以是一个blob对象,必选
 * @param saveName 保存文件名,可选
 */
function openDownloadDialog(url, saveName)
{
    if(typeof url == 'object' && url instanceof Blob)
    {
        url = URL.createObjectURL(url); // 创建blob地址
    }
    var aLink = document.createElement('a');
    aLink.href = url;
    aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
    var event;
    if(window.MouseEvent) event = new MouseEvent('click');
    else
    {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    aLink.dispatchEvent(event);
}

</script>
 </body>
</html>

下载excel文件(支持IE 谷歌等)

axios这里注意type必须为blob
 axios({
                responseType: 'blob',
                method: 'get',
                url: apiExport,
                headers: { "Authorization": 'Bearer ' + this.Token, 'Content-Type': 'application/json;charset=utf-8' },
                params: {
                    Marketing: this.SearchMarketingIdList,
                    Status: this.SearchStatus,
                    Operator: this.SearchOperationList,
                    Sku: this.Sku,
                },
            })
            .then(function (response) {
                Swal.fire({
                    showConfirmButton: false,
                    timer: 1
                });
                var blob = new Blob([response.data])
                if (!!window.ActiveXObject || "ActiveXObject" in window) {
                    window.navigator.msSaveOrOpenBlob(blob, '用户数据.xlsx');
                } else {
                    var downloadElement = document.createElement('a');
                    var href = window.URL.createObjectURL(blob); //创建下载的链接
                    downloadElement.href = href;
                    downloadElement.download = '用户数据.xlsx'; //下载后文件名
                    document.body.appendChild(downloadElement);
                    downloadElement.click(); //点击下载
                    document.body.removeChild(downloadElement); //下载完成移除元素
                    window.URL.revokeObjectURL(href); //释放掉blob对象 
                }          
            })
            .catch(function (error) {
                Swal.fire({
                    icon: 'error',
                    title: 'System Error',
                    showConfirmButton: false,
                    timer: 1500
                })
                console.log(error);
            });
评论