【问题标题】:Generating file with ajax and allow user to download it?用ajax生成文件并允许用户下载?
【发布时间】:2011-10-05 20:19:14
【问题描述】:

我有与此非常相似的问题:Allowing users to download files - ASP.NET,但在我的情况下,我正在使用 ajax 生成 xlsx 文件,并且在我正在使用的 ajax 调用的 aspx 页面上:

Response.Clear();
Response.ContentType = "application/octet-stream";
string filename = User.Identity.Name + "_Report.xlsx";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
Response.WriteFile(AppDomain.CurrentDomain.BaseDirectory + "Reports\\" + filename);
Response.End();

生成此文件时,控制权返回给 ajax 调用页面,并且我不想显示基于此 ajax 响应的保存文件对话框并允许用户下载此生成的文件。我不想使用 ajax 调用页面将文件保存在磁盘上,然后将 ajax 调用页面重定向到该文件,因为 IE 中的弹出窗口阻止程序。我正在使用 jquery 进行 ajax 调用:

$.ajax({  
    type:"POST", 
    url: "AjaxReport.aspx",               
    data:dataString,
    success: function(data) {
        //don't want to use this  
        // $('#RedirectIFrame').attr('src','Reports/Report.xlsx?cache='+Math.random());
        //want to use data variable containing ajax response (bytes of Report file) showing
        //save dialog to download this file from browser
    }              
});   

如何做到这一点?

【问题讨论】:

    标签: javascript asp.net jquery ajax


    【解决方案1】:

    目前 JavaScript 无法访问用户的文件系统,这意味着您无法提示用户保存来自网络流的文件。

    换句话说。您需要执行该重定向并将文件流写入 HTTP 响应,并让用户决定要做什么:)

    【讨论】:

      猜你喜欢
      • 2010-10-15
      • 2018-12-15
      • 2023-03-21
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 2014-02-26
      相关资源
      最近更新 更多