我的服务器动态生成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进行标题授权
答案 0 :(得分:1)
通过添加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) }
});