So I'm working on a website that needs to make a call to the server and it returns a zip file, the thing is that I'm not entierly sure I'm doing everything right. The code looks kind of like this:
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
});
}
}
As you can see I need to makeup the file with the byte array that is in the response, how can I do that?
An approach utilizing
XMLHttpRequest()
; check ifa
element hasdownload
property, if true, setdownload
property to anobjectURL
; else, usewindow.open()
with parameterobjectURL
ofBlob
responsejQuery version using fork of
jquery-ajax-blob-arraybuffer.js
You can use
<a>
element,download
attributeAlternatively parse file using a library, e.g.,
zip.js
, create multiple or single downloadable.zip
from data contained within file.Create an objectURL of each file, download each file using
a
element.If
download
attribute is not available at browser, you can usedata URI
of file object withMIME
type set toapplication/octet-stream
to download file