简体   繁体   中英

href for downloading an excel file

My server generates excel files dynamically. I am using AJAX to download the dynamic excel file. In success callback, I receive the excel file data.

    $.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) }
        });

Please suggest how to use this data in the href attribute of anchor tag for downloading ?

Note:

1) I need AJAX for header authorization

Improve your request by adding dataType: "binary" and responseType: "arraybuffer" property.

$.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) }
});

Then you receive array buffer which can be easily download via Blob and object URL.

var blob = new Blob([arraybuffer], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);

in your case:

$.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) }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM