Jaz
Jaz

Reputation: 135

Send all image files from node.js to frontend

How can I send all image files from my backend nodejs server folder to my Reactjs client? I have created a web upload site where each user can signin and upload their files. So whenever a user signs-in, I want all the files he/she has uploaded to be visible on website.
res.sendFile didn't help. I found out that it does not send multiple files at once. So far it is only sending 1 single file (console log shows all the files) that is visible on the client side.

Nodejs:

    function getFiles (dir, files_){
    files_ = files_ || [];
    var files = fs.readdirSync(dir);
    for (var i in files){
        var name = dir + '/' + files[i];
        if (fs.statSync(name).isDirectory()){
            getFiles(name, files_);
        } else {
            files_.push(name);
        }
    }
    return files_;
    }

  app.get('/loadit', verifyToken, (req, res) => {
  var loadFiles = getFiles(__dirname + /data/);
   jwt.verify(req.token, 'secretkey', (err, decoded) => {
    if(err) {
      res.sendStatus(403);
    } else {
        loadFiles.map((data1) => { 
          console.log(data1);
          return res.sendFile(data1)
      })
    }
  })
});

Is there any different approach for doing the same task? I also thought about sending all the images link as a json list to the frontend (reactjs) and then requesting images link from my nodejs server. I don't know if that is a good idea at all.

Upvotes: 2

Views: 3215

Answers (2)

H R
H R

Reputation: 1

You can never send more than one file at a time, if you want to send all the images of the user, you should send a json array with all of his images, and on the frontend fetch them one by one.

Upvotes: 0

user9906968
user9906968

Reputation:

You can generate an archive file (like zip) on the fly at the server to download all images, e.g. with https://github.com/archiverjs/node-zip-stream to make a zip file with all images.

If you want to show all images, add an API to get a list of filenames and an other one to get a specific image file.

Upvotes: 1

Related Questions