2012-12-20 1290 views
1
base64编码文件

我有以下的Ajax调用:不能下载IE

$.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中,我得到了以下错误:“该网页无法在这个网页displayed.Some内容或文件要求您没有安装的程序。”

回答

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

工作