2014-03-26 105 views
0

我有一個ajax請求上傳文件和其他一些數據,解析它,並以xls格式下載。我目前使用ajax正確地上傳文件,但是當成功函數被調用時,它會接收二進制數據作爲其參數'data'。我想採用這些數據並用它創建一個文件,並將其呈現給用戶,就好像它已經被下載一樣。這可能嗎?這是我的ajax請求。Ajax請求接收二進制數據

$("#fileForm").submit(function(){ 
    var fileData = $("#fileInputElmt").prop("files")[0]; 
    var data = new FormData(); 
    data.append("upload",fileData); 
    var url = "process.action?" + $("#fileForm").serialize(); 
    console.log(url); 
    console.log(data); 
    $.ajax({ 
     type: "POST", 
     url:url, 
     data:data, 
     cache:false, 
     contentType:false, 
     processData:false, 
     success:function(data){ 
      console.log("success"+data); 
      hideProgressBar(); 
     },error:function(data){ 
      console.log("error "+data); 
      hideProgressBar(); 
     } 
    }); 
    return false; 
}); 

回答

1

您正在尋找類似的東西。

function downloadPDF() { 

var xhr = new XMLHttpRequest(); 
xhr.open('POST', API_URL, true); 
xhr.responseType = 'arraybuffer'; 

xhr.onload = function(e) { 
    if (this.status == 200) { 
     var bb = new window.WebKitBlobBuilder(); 
     bb.append(this.response); // Note: not xhr.responseText 

     var blob = bb.getBlob('application/pdf'); 
     var blobURL = window.webkitURL.createObjectURL(blob); 

     window.open(blobURL); 
    } 
}; 

xhr.send(createRequest()); 
} 

只能在新的瀏覽器,Chrome瀏覽器IE9 +等..

的例子用戶XHR,但如果你的Ajax調用返回的二進制,你應該能夠做同樣的事情。

相關問題