2、前端頁面未設置字符集編碼;
3、需要在ajax中添加 request.responseType = “arraybuffer”;
經(jīng)過不斷測試,我的應該是第三點導致。但在jquery ajax 中添加后仍然不起作用,亂碼問題始終無法解決。
第二版
主要代碼
前端,使用原生的ajax。后端未變動。
var xhr = new XMLHttpRequest();
xhr.responseType = "arraybuffer";
xhr.open("POST", url, true);
xhr.onload = function () {
const blob = new Blob([this.response], {type:"application/vnd.ms-excel"});
if(blob.size < 1) {
alert('導出失敗,導出的內容為空!');
return;
}
if(window.navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, 'test.xls')
} else {
const aLink = document.createElement('a');
aLink.style.display = 'none';
aLink.href = window.URL.createObjectURL(blob);
aLink.download = 'testxls';
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
return;
}
}
xhr.setRequestHeader("Authorization", "xxx");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify(queryParams));
測試結果
下載的excel不再亂碼,原生ajax中使用 “arraybuffer” 使用是生效的。
總結
“arraybuffer” 這個參數(shù)導致的excel導出亂碼,在原生的ajax中設置是有效的,在jquery的ajax中暫時還沒找到生效的方式。
更多關于云服務器,域名注冊,虛擬主機的問題,請訪問西部數(shù)碼官網(wǎng):m.ps-sw.cn