1. 程式人生 > >axios下載檔案亂碼問題 無法解壓 檔案損壞

axios下載檔案亂碼問題 無法解壓 檔案損壞

        /* 下載附件 */
        downloadFile(fileName) {
            // window.open(url);
            var that = this;
            var url = "PO2116"; //介面地址
            that.$http
                ({
                    url:url + "?filePath=" + fileName,
                    method: 'post',
                    headers:{
                        'Content-Type': 'application/json; application/octet-stream'
                    },
                    responseType: 'blob',
                })
                .then(res => {
                    console.log(res)
                    const blob = new Blob([res.data]);
                    const downloadElement = document.createElement("a");
                    const href = window.URL.createObjectURL(blob);
                    //後臺再header中傳檔名
                    const name = fileName;
                    downloadElement.href = href;
                    downloadElement.download = name;
                    document.body.appendChild(downloadElement);
                    downloadElement.click();
                    document.body.removeChild(downloadElement); // 下載完成移除元素
                    window.URL.revokeObjectURL(href); // 釋放掉blob物件


                });
        },

這倆是重點

headers:{
           'Content-Type': 'application/json; application/octet-stream'
},
 responseType: 'blob',

我單獨加一個responseType 下載下來還是亂碼  加了header就好了