美文网首页VUEtool
ElementUI 文件流下载

ElementUI 文件流下载

作者: Cherry丶小丸子 | 来源:发表于2021-05-26 11:47 被阅读0次

    方法封装

    /**
     * 二进制流下载
     * @param {Object} res
     */
    binaryDownload(res){
        if(!res.data){
            this.$message.error("文件下载失败!");
            return false;
        }
        
        // 这里res.data是返回的是二进制文件流
        const blob = new Blob([res.data], {type: 'application/octet-stream', endings: 'transparent'}); // 将二进制文件流转为blob
        
        let contentDisposition = res.headers['content-disposition']; // 从Response Headers中获取content-disposition的值, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
        let patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*'); // 设置正则表达式匹配格式
        // let patt = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; // 设置正则表达式匹配格式
        let result = patt.exec(contentDisposition); // 通过正则表达式提取“filename=” 后的值
        let filename = result[1]; // 提取文件名
        
        // 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(blob, decodeURI(filename));
        }else{
            const blobURL = window.URL.createObjectURL(blob); // 把blob转化为一个Blob URL
            
            const aLink = document.createElement('a'); // 创建a标签,用于跳转至下载链接
            aLink.href = blobURL; // 设置a标签href值
            aLink.setAttribute('download', filename); // 设置下载文件名称
    
            // if (res.config.params.fileType == undefined || res.config.params.fileType == '' || res.config.params.fileType == null) {
            //  aLink.setAttribute('download', res.config.params.fileName); // 设置下载文件名称
            // } else {
            //  aLink.setAttribute('download', res.config.params.fileName + '.' + res.config.params.fileType); // 设置下载文件名称
            // }
    
            // 兼容:某些浏览器不支持HTML5的download属性
            if (typeof aLink.download === 'undefined') {
                aLink.setAttribute('target', '_blank');
            }
            aLink.style.display = 'none'; // 隐藏a标签
            document.body.appendChild(aLink); // a标签插入到body中
            aLink.click(); // 模拟a标签点击事件 使其下载
            document.body.removeChild(aLink); // 移除a标签
            window.URL.revokeObjectURL(blob); //释放掉blob对象
        }
    }
    

    调用接口

    this.$axios.product.productRepositoryFileDown({
        params:{
            // *****
        },
        timeout: 0, // 0为取消超时
        responseType: "blob", // 下载必须指定服务器响应的数据类型
        headers: {
            "Content-Type": "application/json;application/octet-stream"
        }
    }).then(res => {
        // 此处为下载
        this.$utils.binaryDownload(res);
    })
    

    相关文章

      网友评论

        本文标题:ElementUI 文件流下载

        本文链接:https://www.haomeiwen.com/subject/wykksltx.html