2012-03-08 4 views
7

Sto effettuando una chiamata ajax a un'API che restituisce dati binari. Mi chiedo se è possibile prendere quei dati binari e visualizzarli per il cliente in una nuova finestra? Questo è quello che sto facendo adesso. Il problema è che il documento si apre, ma è completamente vuoto.Scarica dati binari come file tramite Javascript

$.ajax({ 
    type: "POST", 
    url: apiURL, 
    data: xmlRequest, 
    complete: function(xhr, status) { 
     var bb = new window.WebKitBlobBuilder(); 

     // Append the binary data to the blob 
     bb.append(xhr.responseText); 

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

Qualche idea?

+0

Stai utilizzando HTTPS con IE? In tal caso, consulta http://stackoverflow.com/questions/773308/ie-https-generating-pdf-from-php-file-doesnt-work –

+0

È un'estensione di Chrome, quindi non devo preoccuparmi di IE. – Anton

+0

hai il controllo dell'implementazione lato server? –

risposta

7

Va bene, ho capito. Ho dovuto specificare responseType come 'array buffer':

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()); 
} 
+0

Come si modifica il nome del file scaricato con questo metodo? – Greg

+1

utilizzando FileSaver lo renderà più semplice http://stackoverflow.com/questions/15211742/html5-saveas-support-in-google-chrome – davyzhang