1

When I make a request to the server it returns a stream zip

const response = await axios.get('http://192.168.1.100:3030', {
    params: this.getParams(),
    responseType: 'blob' 
});

console.log(response.data);

I want to get the contents of this zip without saving the file. But, if I try to catch the content with "new Blob" comes something like:

PK ¥ZksÛÆ=³þ~ç§N;1  d2Ã,S!EÔ_2­¦ÎÈ+Ûéã×ö§ôîÙ%........

However, the expected value is

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

I found this example similar. But, it does not work for me: Decompress gzip and zlib string in javascript

Would it be possible to get the contents of this zip that is in memory without having to save it?

1 Answers1

0

As others have mentioned you need to unzip the zip on the client-side to actually see the contents of the zip. For the browser the blob is just a bunch of binary data without any meaning. If you take a closer look at the output you get:

PK ¥ZksÛÆ=³þ~ç§N;1

you can at least see that it's a zip file because of the initial PK. It's part of a zip files header.

A pretty popular Javascript library for zip operations is JSZip.

Here's an example which loads a zip file containing JqueryUI (due to CORS restrictions we have to get it via a proxy - yacdn.org). After successful loading, JSZip is used to get a list of the files inside the zip archive. This is done using JSZip's loadAsync method and passing it the blob as parameter.

 zip.loadAsync(response.data).then(function(contents) {
   console.log(Object.keys(contents.files));
 });

The returned array of files contains a text file jquery-ui-1.12.1/AUTHORS.txt If we want to see the actual file - and since you tried to view a text file too - we need some more code.

contents.files["jquery-ui-1.12.1/AUTHORS.txt"].async("string").then(function(data) {
      console.log(data);
    });

The complete code:

async function loadZip() {
  const response = await axios.get('https://yacdn.org/serve/https://jqueryui.com/resources/download/jquery-ui-1.12.1.zip', {
    responseType: 'blob'
  });

  var zip = new JSZip();
  zip.loadAsync(response.data).then(function(contents) {
    console.log(Object.keys(contents.files));
    contents.files["jquery-ui-1.12.1/AUTHORS.txt"].async("string").then(function(data) {
      console.log(data);
    });
  });
}
loadZip();
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.0/jszip.min.js"></script>
obscure
  • 11,916
  • 2
  • 17
  • 36