1

I am getting a response from a rest api whose Content-Type is text/html and Content-Encoding is gzip.

I tried to download it using blob

const blob = new Blob([res], { type: 'application/gzip' });
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement('a'); 
a.href = downloadUrl;
document.body.appendChild(a);
a.click();

But the downloaded gz file was not able to open (seems to be corrupted). can some one help me with downloading zip file in reactjs.

Edit: require a solution without using any external plugins

qaz2625 qaz
  • 103
  • 2
  • 2
  • 10

1 Answers1

4

you can use jszip npm module.

For example:

var zip = new JSZip();

zip.file("Hello.txt", "Hello World\n");
var img = zip.folder("images"); //images is the folder which will be zip

img.file("smile.gif", imgData, {base64: true});

zip.generateAsync({type:"blob"}).then(function(content) {

    saveAs(content, "example.zip");
});

To use it without jszip, you can try the following code:

function str2bytes (str) {
    var bytes = new Uint8Array(str.length);
    for (var i=0; i<str.length; i++) {
        bytes[i] = str.charCodeAt(i);
    }
    return bytes;
}

and its usage:

var blob = new Blob([str2bytes(myData)], {type: "application/zip"});
saveAs(blob, "data.zip"); 

But jszip is a better alternative approach.

Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75