2012-12-20 1285 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

工作