2016-07-04 7 views
1

Also arbeite ich an einer Website, die einen Anruf an den Server machen muss und es eine Zip-Datei zurückgibt, die Sache ist, dass ich nicht ganz sicher bin, dass ich tue alles richtig. Der Code sieht ein bisschen wie folgt aus:Eine Zip-Datei als Antwort auf AJAX-Anfrage erhalten

function download(){ 
    if($('.download').hasClass('activeBtn')){ 
    $.ajax({ 
     type: 'GET', 
     url: someUrl, 
     contentType: 'application/zip', 
     dataType: 'text', 
     headers: { 
      'Api-Version': '3.4' 
     } 

    }).then(function (data) { 
     console.log(data); //Basically prints the byte array 
     //Here I should build the file and download it 
    }); 
    } 
} 

Wie Sie ich brauche die Datei mit dem Byte-Array zu Make-up sehen, die in der Antwort ist, wie kann ich das tun?

+0

zum Download Was planen Sie mit der Zip-Datei in Javascript zu tun? Möchten Sie den Benutzer herunterladen? Oder willst du es mit Javascript manipulieren? – DutchKevv

+0

@ DutchKev Nur müssen Sie es herunterladen, das ist alles –

Antwort

1

Ein Ansatz unter Verwendung XMLHttpRequest(); Überprüfen Sie, ob a Element download Eigenschaft hat, wenn wahr, download Eigenschaft auf eine objectURL setzen; , Sonst window.open() mit dem Parameter objectURL von Blob Antwort

function downloadFile(url, headers, filename) { 

    function handleFile(data) { 
    console.log(this.response || data); 
    var file = URL.createObjectURL(this.response || data); 
    filename = filename || url.split("/").pop(); 
    var a = document.createElement("a"); 
    // if `a` element has `download` property 
    if ("download" in a) { 
     a.href = file; 
     a.download = filename; 
     document.body.appendChild(a); 
     a.click(); 
     document.body.removeChild(a); 
    } else { 
     // use `window.open()` if `download` not defined at `a` element 
     window.open(file) 
    } 
    } 

    var request = new XMLHttpRequest(); 
    request.responseType = "blob"; 
    request.onload = handleFile; 
    request.open("GET", url); 
    for (var prop in headers) { 
    request.setRequestHeader(prop, headers[prop]); 
    } 

    request.send(); 
} 

downloadFile("/path/to/resource/", {"x-content": "abc"}, "filename.zip") 

jQuery-Version mit fork von jquery-ajax-blob-arraybuffer.js

/** 
* 
* jquery.binarytransport.js 
* 
* @description. jQuery ajax transport for making binary data type requests. 
* @version 1.0 
* @author Henry Algus <[email protected]> 
* 
*/ 

// use this transport for "binary" data type 
$.ajaxTransport("+binary", function(options, originalOptions, jqXHR){ 
    // check for conditions and support for blob/arraybuffer response type 
    if (window.FormData && ((options.dataType && (options.dataType == 'binary')) 
     || (options.data 
     && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) 
     || (window.Blob && options.data instanceof Blob)))) 
     ) 
    { 
     return { 
      // create new XMLHttpRequest 
      send: function(headers, callback){ 
     // setup all variables 
       var xhr = new XMLHttpRequest(), 
     url = options.url, 
     type = options.type, 
     async = options.async || true, 
     // blob or arraybuffer. Default is blob 
     dataType = options.responseType || "blob", 
     data = options.data || null, 
     username = options.username || null, 
     password = options.password || null; 

       xhr.addEventListener('load', function(){ 
      var data = {}; 
      data[options.dataType] = xhr.response; 
      // make callback and send data 
      callback(xhr.status 
        , xhr.statusText 
        , data 
        , xhr.getAllResponseHeaders()); 
       }); 

       xhr.open(type, url, async, username, password); 

     // setup custom headers 
     for (var i in headers) { 
      xhr.setRequestHeader(i, headers[i]); 
     } 

       xhr.responseType = dataType; 
       xhr.send(data); 
      }, 
      abort: function(){ 
       jqXHR.abort(); 
      } 
     }; 
    } 
}); 
function downloadFile(url, headers, filename) { 
return $.ajax({ 
    url:url, 
    dataType:"binary", 
    processData: false, 
    headers:headers 
}) 
.then(function handleFile(data) { 
    console.log(this.response || data); 
    var file = URL.createObjectURL(this.response || data); 
    filename = filename || url.split("/").pop(); 
    var a = document.createElement("a"); 
    // if `a` element has `download` property 
    if ("download" in a) { 
     a.href = file; 
     a.download = filename; 
     document.body.appendChild(a); 
     a.click(); 
     document.body.removeChild(a); 
    } else { 
     // use `window.open()` if `download` not defined at `a` element 
     window.open(file) 
    } 
    }) 
} 

downloadFile("/path/to/resource/", {"x-custom-header":"abc"}, "filename.zip"); 

Einfach herunterladen, um es zu verwenden, das ist alles

können <a> Element verwenden, download Attribut

$("<a>", {href: someUrl, 
     download: "filename.zip" 
}).appendTo("body")[0].click() 

Alternativ Datei parsen eine Bibliothek unter Verwendung beispielsweise zip.js, erstellen mehrere oder einzelne herunterladbare .zip von Daten in der Datei enthalten ist.

Erstellen Sie ein objectURL jeder Datei, laden Sie jede Datei mit dem Element a herunter.

Wenn download Attribut im Browser nicht verfügbar ist, können Sie data URI von Dateiobjekt mit MIME Typ application/octet-stream gesetzt verwenden Datei

+1

beachten Sie, dass 'Download' noch Cross-Browser-Support-Probleme hat http://caniuse.com/#feat=download – charlietfl

+1

@charlietfl Ja, enthalten Beschreibung der alternativen Ansatz mit' Daten-URI' , 'application/octet-stream', um die Datei herunterzuladen, wenn' download' Attribut nicht im Browser verfügbar ist – guest271314

+0

@ guest271314 Ok ja, ich habe vergessen anzugeben, dass ich einige benutzerdefinierte Header sende, also ja, mein Fehler. Irgendwelche Ideen dafür? –

Verwandte Themen