Search code examples
node.jsmongodbexpressadm-zip

Trying to download files using express and node js


Here is my block of code.

app.get('/download/:id', async(req,res) =>{
    const {id} = req.params;
    const staffDoc = await Staff.findById(id);
    var to_zip = fs.readdirSync(__dirname + `/uploads/${staffDoc.profile}`);
    const zip = new admzip();
        for(let i = 0; i < to_zip.length;i++){
            zip.addLocalFile(to_zip[i])
        };

        const file_after_download = 'downloaded_file.zip';

        const data = zip.toBuffer();

        res.set('Content-Type', 'application/octet-stream');
        res.set('Content-Disposition', `attachment; filename=${file_after_download}`);
        res.set('Content-Length', data.length);
        res.send(data);
    
});

I made a site that at the moment you can upload files but it will be stored on the local directory '/uploads' The local directory the files are stored But files will name/id will be stored on mongodb in an array named profile. how the files name are stored in mongodb Now I'm trying to download certain files based on their name/id stored in the array profile. But it doesnt work it keepson giving me an error the error i keep getting

I've also tried:

const x = __dirname+"/uploads/";
            res.zip([
                 {
                   path : x + staffDoc.profile[0],
                    name : staffDoc.profile[0]
                }
             ])
        

This worked but i can't seem to wrap a loop around it so I'll be able to download all the files and don't know anyother way.


Solution

  • Use map

    res.zip(
      staffDoc.profile.map((p) => ({
        path: x + p,
        name: p,
      })),
    );