注意:1. 确认后端返回的blob中文未乱码(后端返回的中文乱码需要后端解决)
2. 后端返回blob中文未乱码,前端下载的csv文件中文乱码,解决方案如下:取消 request.responseType = 'blob'; 配置 ,然后转blob时添加 "\uFEFF" + this.response
var request = new XMLHttpRequest();
var url = 'http://xxx/loadCsv' //接口地址
request.open('post', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
// request.responseType = 'blob'; //csv文件不用配置blob
request.onload = function (e) {
if (this.status === 200) {
const contentTypeHeader = request.getResponseHeader("Content-Type");
//"\uFEFF"解决中文乱码问题
const blob = new Blob(["\uFEFF" + this.response], { type: contentTypeHeader });
//兼容ie
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveBlob(blob, "API测试数据.csv");
} else {
var downloadLink = window.document.createElement('a');
downloadLink.href = window.URL.createObjectURL(blob);
downloadLink.download = "API测试数据.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
}
};
request.send()