href用于下载一个excel文件

我的服务器dynamic生成excel文件。 我正在使用AJAX下载dynamic的Excel文件。 在成功callback中,我收到了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) } }); 

请build议如何在锚标签的href属性中使用这些数据进行下载?

注意:

1)我需要AJAX头标授权

通过添加dataType: "binary"提高你的请求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) } });