【问题标题】:href for downloading an excel file用于下载 excel 文件的 href
【发布时间】:2017-05-23 06:52:35
【问题描述】:

我的服务器动态生成 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 来进行标头授权

【问题讨论】:

    标签: javascript ajax excel download


    【解决方案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) }
    });
    

    【讨论】:

    • 谢谢,我试试看
    • 问题是从服务器返回 excel 文件作为数组缓冲区。我无法控制来自服务器的数据。第三方库将其直接返回给客户端浏览器。我只是将我的数据传递给第 3 方库
    • 是否可以在客户端将数据转换为数组缓冲区?
    • 你必须向库传递什么以及从库中输出什么?
    • 我正在传递一个第 3 方图表实例。他们的库将创建一个带有图表的 excel 文件。输出是生成的excel文件的原始数据。
    猜你喜欢
    • 2014-08-06
    • 2014-12-05
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    相关资源
    最近更新 更多