我的服务器动态生成excel文件。我正在使用 AJAX 下载动态 excel 文件。在成功回调中,我收到了 excel 文件数据。
$.ajax({
url: exporting.action,
headers: { "Authorization": "Basic " + btoa("key : " + key) },
type: "post",
success: function(res){
//res is the excel file that needs to be downloaded
//I know we can download image using anchor tag but not sure about excel file
},
data: { 'Model': JSON.stringify(modelClone) }
});
请建议如何在href
锚标签的属性中使用这些数据进行下载?
笔记:
1) 我需要 AJAX 进行标头授权
通过添加dataType: "binary"
和responseType: "arraybuffer"
属性改进您的请求。
$.ajax({
url: exporting.action,
headers: { "Authorization": "Basic " + btoa("key : " + key) },
type: "post",
responseType: "arraybuffer",
dataType: "binary",
success: function(res){
//res is the excel file that needs to be downloaded
//I know we can download image using anchor tag but not sure about excel file
},
data: { 'Model': JSON.stringify(modelClone) }
});
然后你会收到数组缓冲区,它可以通过 Blob 和对象 URL 轻松下载。
var blob = new Blob([arraybuffer], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
在你的情况下:
$.ajax({
url: exporting.action,
headers: { "Authorization": "Basic " + btoa("key : " + key) },
type: "post",
success: function(res){
var blob = new Blob([res], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
},
data: { 'Model': JSON.stringify(modelClone) }
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句