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_2283267
5. 前端處理文件流自動下載並兼容ie9+ https://blog.csdn.net/skye_Z/article/details/81135540


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM