【问题标题】:Can't download base64 encoded files in IE无法在 IE 中下载 base64 编码文件
【发布时间】:2012-12-20 13:24:01
【问题描述】:

我有以下 Ajax 调用:

    $.ajax({
    type: 'POST',
    url: 'AJAX.aspx/DownloadFile',
    data: {},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data)
    {
        window.location.href = 'data:txt/octet-stream;base64, ' + data.d;
    },
    error: function (x, e)
    {
        alert("The call to the server side failed. " + x.responseText);
    }
});

这是我的服务器端代码:

[WebMethod]
public static string DownloadFile(){
    HttpResponse response = HttpContext.Current.Response;
    response.AppendHeader("Content-Disposition", "attachment;filename=b.txt");
    FileStream fs = new FileStream("C:/b.txt", FileMode.OpenOrCreate);
    byte[] data=new byte[fs.Length];
    fs.Read(data, 0, (int)fs.Length);        
    fs.Close();
    return Convert.ToBase64String(data);
}

这里有两个问题:

  1. 在 Opera、Firefox 和 Chrome 中,我可以下载由服务器发送的 base64 二进制数据组成的文件。唯一的问题是文件名是浏览器默认的。在 Opera 中是“默认”,在 Chrome 中是“下载”,在 Firefox 中是这样的:“lpyQswKF.part”。如何手动分配名称?

  2. 在 IE 中出现以下错误:“无法显示网页。此网页上的某些内容或文件需要您未安装的程序。”

【问题讨论】:

    标签: asp.net ajax internet-explorer download


    【解决方案1】:

    您可以像这样分配文件名:

    var a = document.createElement("a");
    
    a.download = "file name";
    
    a.href = 'data:txt/octet-stream;base64,' + data.d;
    
    document.body.appendChild(a);
    
    a.click();
    

    我还在寻找如何让它在 IE 中运行

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      相关资源
      最近更新 更多