1

I'm looking for away to send multiple images in one GET request from an Expressjs server through an api.

I want to create an image gallery of each users uploaded images in a MEAN stack. When images are uploaded using multer, the image information is saved to mongodb, including the userid of whoever uploaded it.

When on angularjs, I want user to have access to any of the images they have previously uploaded. Currently I'm sending one file on a GET request based on user id. Is there anyway of sending multiple files in one json. I'm currently using Expressjs's res.sendFile, but haven't found any info about sending multiple back yet.

https://expressjs.com/en/api.html#res.sendFile

Here is my current get request:

exports.getUpload = function(req, res) {
    Upload.find({createdby: req.params.Id}).exec(function(err, upload) {
        errorhandle.errorconsole(err, 'file found');
        console.log(upload[0]);
        var options = {
            root: '/usr/src/app/server/public/uploads/images'
        };
        var name = "" + upload[0].storedname +"";
        console.log(name);
        res.sendFile(name, options,function(err) {
            errorhandle.errorconsole(err, 'file sent');
        });
    });
};
match
  • 10,388
  • 3
  • 23
  • 41

1 Answers1

1

You can't with res.sendFile. In fact I don't think you can at all. Maybe with HTTP/2 Server Push , but I'm not sure.

What you can do is send a JSON response with a link to all the images:

exports.getUpload = async (req, res) => {
    const uploads = await Upload.find({ createdby: req.params.Id }).exec()
    const response = uploads.map(image => {name: `https://example.com/uploads/images/${image.storedname}`})
    res.json(response)
}

Note error handling omitted.

Cisco
  • 20,972
  • 5
  • 38
  • 60