jquerynode.jszip

Not able to send zip file from nodejs express backend to jquery frontend for automatic download


i have a few files in a folder, want them to be downloaded at client side when a button is clicked, so i zip them using adm-zip which works fine following is my backend code

const zip = new AdmZip();
zip.addFile(/e/Projects/NodeJs/lknkjnknb/lknkjnknb.pdf);
zip.addFile(/e/Projects/NodeJs/lknkjnknb/lknkjnknb2.pdf);
zip.writeZip('/Projects/NodeJs/lknkjnknb.zip'); //  this works fine, zip is good
const data = zip.toBuffer();

res.set('Content-Type','application/octet-stream');
res.set('Content-Disposition',attachment; filename=lknkjnknb.zip);
res.set('Content-Length',data.length);
res.send(data);

following is my frontend jquery ajax call - this does not work as expected, zip file is downloaded but zip file does not contain any files and is corrupted

$.ajax({

                url: url,
                type: "GET",
                responseType: 'arraybuffer',

                    success: async function(response){
                            const url = window.URL.createObjectURL(new Blob([response]));
                            const link = document.createElement('a');
                            link.href = url;
                            link.setAttribute('download', prj+'.zip');
                            document.body.appendChild(link);
                            link.click();
                    },
                error: function (error) {
                    console.log(Error ${error});
                }
                });

Solution

  • Your jQuery request settings are not correct: responseType should be set under xhrFields, see jQuery.ajax( [settings ] ) > xhrFields

    So, replace:

    responseType: 'arraybuffer',
    
    with:
    xhrFields: {
         responseType: 'arraybuffer'
    },
    

    full code:

    $.ajax({
    
        url: url,
        type: "GET",
        xhrFields: {
            responseType: 'arraybuffer'
        },
    
        success: async function(response) {
            const url = window.URL.createObjectURL(new Blob([response]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', prj + '.zip');
            document.body.appendChild(link);
            link.click();
        },
        error: function(error) {
            console.log(Error $ {
                error
            });
        }
    });