Vue 採用blob下載後端返回的excel流文件亂碼問題

  1. 沒有文件服務器, 先後端採用文件流方式下載,後端返回二進制亂碼時,前端使用blob對象進行處理
    2.採用的是axios請求方式
  2. this.$http.post("download", { fileName: file.filename })
    .then(function(response) {
    let blob = new Blob([response.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
    let downloadElement = document.createElement('a');
    let href = window.URL.createObjectURL(blob); //建立下載的連接
    downloadElement.href = href;
    downloadElement.download = 'xxx.xlsx'; //下載後文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //點擊下載
    document.body.removeChild(downloadElement); //下載完成移除元素
    window.URL.revokeObjectURL(href); //釋放掉blob對象
    })

3.1
this.$http.post("download", { fileName: file.filename } ,{responseType: 'arraybuffer'}) // 或者responseType: 'blob'
.then(function(response) {前端

let blob = new Blob([response.data], {type: 'application/vnd.ms-excel'});

                    if (window.navigator.msSaveOrOpenBlob) {
                           //兼容ie
                        window.navigator.msSaveBlob(blob, file.filename);

                    } else {

                        let downloadElement = document.createElement('a');
                        let href = window.URL.createObjectURL(blob); //建立下載的連接
                        downloadElement.href = href;

                        downloadElement.download =  file.filename;//下載後文件名


                        document.body.appendChild(downloadElement);
                        //此寫法兼容火狐
                        let evt = document.createEvent("MouseEvents");
                        evt.initEvent("click", false, false);
                        downloadElement.dispatchEvent(evt);

                        document.body.removeChild(downloadElement);
                    }

   })

4.分享連接 https://www.oschina.net/question/3910533_2283267ios

  1. 前端處理文件流自動下載併兼容ie9+ http://www.javashuo.com/article/p-opmexngr-nc.html
相關文章
相關標籤/搜索