Dynamically create and stream zip to client

后端 未结 4 1310
滥情空心
滥情空心 2020-12-02 11:36

I am using NodeJs (w/express) and I am trying to stream a zip file back to the client. The files contained in the zip do not live on the file system, rather they are create

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 12:15

    Sending a zip file as binary data with expressjs and node-zip:

    app.get("/multipleinzip", (req, res) => {
        var zip = new require('node-zip')();
        var csv1 = "a,b,c,d,e,f,g,h\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8";
        zip.file('test1.file', csv1);
        var csv2 = "z,w,x,d,e,f,g,h\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8";
        zip.file('test2.file', csv2);
        var csv3 = "q,w,e,d,e,f,g,h\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8";
        zip.file('test3.file', csv3);
        var csv4 = "t,y,u,d,e,f,g,h\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8\n1,2,3,4,5,6,7,8";
        zip.file('test4.file', csv4);
        var data = zip.generate({base64:false,compression:'DEFLATE'});
        console.log(data); // ugly data
        res.type("zip")
        res.send(new Buffer(data, 'binary'));
    })
    

    Creating a download link for the zip file. Fetch data and convert the response to an arraybuffer with ->

        //get the response from fetch as arrayBuffer...
        var data = response.arrayBuffer();
    
        const blob = new Blob([data]);
        const fileName = `${filename}.${extension}`;
        
        if (navigator.msSaveBlob) {
          // IE 10+
          navigator.msSaveBlob(blob, fileName);
        } else {
          const link = document.createElement('a');
          // Browsers that support HTML5 download attribute
          if (link.download !== undefined) {
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', fileName);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        }
    

提交回复
热议问题