vue2使用post请求下载文件

268 阅读1分钟

\qquad又是无力干活的周一,今天突然被通知前端所有的下载文件都要用post请求(来公司以来都是用get下载的),好生气(╬ ̄皿 ̄)!!!这是逼着进步,无力反抗呀|墙|ョ゚ェ゚;)
\qquad来吧,开始搞吧!!!
\qquad首先就要去改请求拦截器,之前封装的请求拦截器不识别blob,进行判断吧

service.interceptors.response.use(
    response => {
        /**
         * code为非success是抛错
         */
        if (response.status === 200) {
            if (response.config.responseType === 'blob') {
                //  判断是否存在要转换的对象
                if (response.data.type === 'application/json') { // 下载文件失败
                    // 实例化 FileReader
                    const reader = new FileReader ()
                    //  读取目标对象 response ,结果用字符形式表达
                    reader.readAsText(response.data , 'utf-8')
                    // 读取完后会获得 reader.result 要转化为可读取的JS对象
                    reader.onload = function() {
                        const {message} = JSON.parse(reader.result)
                        // 弹出转换后的 错误提示
                        Message({
                            showClose: true,
                            message: message,
                            type: 'warning'
                        });
                    }
                    return false;
                }
                return response.data
            }
            const code = response.data.code;
            const res = response.data
            ......下边就是各种code判断啦太多了懒得写了
        }
    },
    error => {
        Vue.prototype.$message({
            showClose: true,
            message: '服务器端错误',
            type: 'error'
        })
        return Promise.reject(error)
    }
)

\qquad这代码写的,我自己都没办法看,但是谁让自己的技术不够呢,能用就用吧(^_−)☆
\qquad这是改完请求拦截器了,为了使用方便直接封装一个utils来耍的撒

api

export function downloadFileData(data, url) {
    return request({
        url: url,
        method: 'post',
        data: data,
        responseType: 'blob',
    }).then((res) => {
        if (res) {
            return res
        }
    })
}

utils

downloadData(downloadUrl, downloadData = null, text, type = 'xlsx') {
  downloadFileData(downloadData, downloadUrl).then((data) => {
    if (data) {
      const fileName = `${text}.${type}`;
      // 将二进制流转为blob
      const blob = new Blob([data]);
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // 兼容IE,window.navigator.msSaveBlob:以本地方式保存文件
        window.navigator.msSaveBlob(blob, decodeURI(fileName));
      } else {
        // 创建新的URL并指向File对象或者Blob对象的地址
        const blobURL = window.URL.createObjectURL(blob);
        // 创建a标签,用于跳转至下载链接
        const tempLink = document.createElement('a');
        tempLink.style.display = 'none';
        tempLink.href = blobURL;
        tempLink.setAttribute('download', decodeURI(fileName));
        // 兼容:某些浏览器不支持HTML5的download属性
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank');
        }
        // 挂载a标签
        document.body.appendChild(tempLink);
        tempLink.click();
        document.body.removeChild(tempLink);
        // 释放blob URL地址
        window.URL.revokeObjectURL(blobURL);
      }
    }
  });
},

\qquad自己纯纯的在这瞎搞(~ ̄▽ ̄)~