0

im trying to add multiple images using react app and send them to backend code to store them in mongodb

here is the code for the backend : link

and this is the frontend link

so this code works for just one image

i need to be able to add multiple images

1 Answer 1

0

Server

Since you are using multer, change the upload.single() function to upload.array().

For example:

app.post("/addItem", 
  upload.array('product-image', 4), // 'product-image' is field name and 4 is the max number of files allowed
  (req, res) => {
    console.log(req.files);
    // ... rest of the logic
  }
)

Check out docs for upload.array()

Client

Change current <input> to allow multiple files:

<input type="file" name="product-image" onChange={this.fileChangeHandler} multiple>

Now save all the images user picked not only the event.target.files[0]:

fileChangeHandler(event) {
    let files = event.target.files
    this.setState({ selectedFiles: files })
}

Now add them in FormData and upload as usual:

let formData = new FormData()
formData.append("product-image", this.state.selectedFiles)

That's it! Hope it helps.

PS: I don't think files should be added to state. You can simply add them to a class variable. In this answer I explained why and how to do that.


Update:

You need to loop over the files now. Your /addItem endpoint's code will look something like this:

app.post("/addItem", upload.array('product-image', 4), (req, res) => {
  console.log(req.files);

  let paths = [];

  req.files.forEach(file => {
    console.log("new file location", file.path)

    let extension = file.originalname.split(".").pop()
    fs.rename(file.path, file.path + "." + extension, () => {})
    paths.push("/" + file.filename + "." + extension);
  });

  console.log("body", req.body)

  let itemToStore = {
    paths: paths,  // notice this `paths` now, it was `path`
    description: req.body.description
  }

  console.log("we are adding", itemToStore)
  itemData.push(itemToStore)
  console.log("updated itemData:", itemData)
  res.send(JSON.stringify(itemData))
})

I didn't modify your code, just added a loop. Your 'path' of undefined error should go away.

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

3 Comments

i tried to do so but it doesn't work there is an error in server that the path is undefined. could you please try it and send me the result? when i upload files it shows me the number of files that i uploaded so the path is not defined. @mehamasum
Please share the full stack trace.
I think I guessed the error. You should loop over the files to save them now. Look at my updated answer.

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.