Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zip File downloaded from ReactJs/Axios is corrupted

I'm trying to download a zip file from a Django api and have the user download it. There are two .csv files in the zip.

I am able to download a single .csv files individually, but when I try to download the zip and unzip, I get errors that the zip is corrupted. For sanity check, I am able to send the request via Postman. I am able to successfully download and unzip the file using that.

Here is my code fragment:

        axios
        .post('http://0.0.0.0:8000/sheets/', data,
            {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'responseType': 'arraybuffer'
                }
            })
        .then(res => {
            console.log(res.data)
            const disposition = res.request.getResponseHeader('Content-Disposition')
            var fileName = "";
            var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
            var matches = filenameRegex.exec(disposition);
            if (matches != null && matches[1]) {
                fileName = matches[1].replace(/['"]/g, '');
            }
            let blob = new Blob([res.data], { type: 'application/zip' })

            const downloadUrl = URL.createObjectURL(blob)
            let a = document.createElement("a"); 
            a.href = downloadUrl;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
like image 385
btbam91 Avatar asked Jan 29 '19 04:01

btbam91


2 Answers

To add to btbam91's reply: responseType has to be part of the config. In the above example:

 axios
    .post('http://0.0.0.0:8000/sheets/', data,
        {
            responseType: 'arraybuffer',
            headers: {
                'Content-Type': 'multipart/form-data',
            }
        })
like image 151
Ciro di Marzo Avatar answered Sep 19 '22 23:09

Ciro di Marzo


The problem was that 'responseType': 'arraybuffer' should not be in "headers."

like image 36
btbam91 Avatar answered Sep 20 '22 23:09

btbam91