2

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So basically I will two APIs, first one to fetch a list of filenames and another to get those images one by one?
If a user has uploaded 1000 files, so the json filenames list will contain all 1000 filenames. Isn't that going to make json too big?
0

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.

4 Comments

So basically I will two APIs, first one to fetch a list of filenames and another to get those images one by one?
Yes, exactly :)
If a user has uploaded 1000 files, so the json filenames list will contain all 1000 filenames. Isn't that going to make json too big?
If a user has uploaded 1000 files, you should use paging.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.