文件下载

解决方法:

1、请求时加上响应类型为blob。 responseType: "blob"

2、通过new blob转码响应

 

blob响应格式结果

 

 

// 文件下载-参考方法一
downloadFile(id,opt) {
                this.$http("fileDownloadPlatform",{ id }, {
                    responseType: "blob",
                }).then((res) => {
                    console.log(res)
                    let blob = new Blob([res], {
                        type: 'application/pdf'
                    })
                    let href = URL.createObjectURL(blob)
                    let downloadElement = document.createElement("a");
                    downloadElement.href = href;
                    downloadElement.download = opt.fileName;
                    document.body.appendChild(downloadElement);
                    downloadElement.click();
                    document.body.removeChild(downloadElement);
                });
            },
//文件下载-参考方法二(没有在new Blob的时候指定MIME类型)
download(url, params, filename, contentType) {
    NProgress.start()
    return service
      .post(url, params, {
        transformRequest: [
          params => {
            let p = contentType && contentType == 'json' ? JSON.stringify(params) : tansParams(params)
            return p
          }
        ],
        headers: {
          'Content-Type': contentType && contentType == 'json' ? 'application/json' : 'application/x-www-form-urlencoded'
        },
        responseType: 'blob'
      })
      .then(r => {
        const content = r.data
        const blob = new Blob([content])
        if ('download' in document.createElement('a')) {
          const elink = document.createElement('a')
          elink.download = filename
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href)
          document.body.removeChild(elink)
        } else {
          navigator.msSaveBlob(blob, filename)
        }
        NProgress.done()
      })
      .catch(r => {
        console.error(r)
        NProgress.done()
        Message({
          message: '下载失败',
          type: 'error',
          duration: messageDuration
        })
      })
  },
posted @ 2022-03-16 14:58  vk隐  阅读(758)  评论(0编辑  收藏  举报