ajax 和 axios请求返回二进制流下载

1、ajax

$.ajax({
url: './logicFile/v1/excelContentCopy',
method: 'POST',
data: formData,
processData: false,
contentType: false,
xhrFields: {
responseType: 'blob' // 确保 responseType 设置正确
},
success: function (response) {
console.log('Response:', response);
console.log('Response type:', response.type); // 检查响应类型
console.log('Response size:', response.size); // 检查响应大小

// 确保 response 是 Blob 对象
if (!(response instanceof Blob)) {
console.error('响应不是 Blob 对象');
return;
}


// 创建 Blob 对象
const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

// 检查浏览器是否支持 msSaveBlob(IE)
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, 'modified_target.xlsx');
} else {
// 其他浏览器
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'modified_target.xlsx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}

// 显示成功消息
$('#responseMessage').text('文件下载成功!').css('color', '#4CAF50');
},
error: function (xhr, status, error) {
console.error('Error:', error);
console.error('Status:', status);
console.error('Response:', xhr.responseText);
// 显示错误消息
$('#responseMessage').text('提交失败,请重试。').css('color', '#F44336');
}
});

2、axios

axios({
method: 'post',
url: './logicFile/v1/excelContentCopy',
data: formData, // 包含文件和其他参数
responseType: 'blob', // 重要:指定响应类型为二进制流
}).then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'modified_target.xlsx'); // 设置下载文件名
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

// 显示成功消息
$('#responseMessage').text('文件下载成功!').css('color', '#4CAF50');
}).catch(error => {
console.error('文件下载失败', error);
// 显示错误消息
$('#responseMessage').text('提交失败,请重试。').css('color', '#F44336');
});


<!-- 响应消息 -->
<div class="response-message" id="responseMessage"></div>


推荐使用 axios,因为它更简洁、功能更强大,且对二进制数据的支持更好。

posted on   0o好好先生o0  阅读(13)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示