4

I have an array of objects in the format:

array1: [ { name: 'A', image: File {name: "Desert.jpg", path: "C:\Users\Public\Pictures\Sample Pictures\Desert.jpg", lastModified: 1247549551658, lastModifiedDate: Tue Jul 14 2009 11:02:31 },
          { name: 'B', image: File{name: "Desert.jpg", path: "C:\Users\Public\Pictures\Sample Pictures\Tulips.jpg", lastModified: 1247549551658, lastModifiedDate: Tue Jul 14 2009 11:02:31} }, ..... ]

I am sending the array1 to my back end server using:

formData.append('array1', JSON.stringify(array1))

In the back end I am receiving the array as :

let array1 = JSON.parse(req.body.array1)

But in the back end, the File is empty. How can I fix this?? The front end is in React and backend in Node.

3
  • Does your backend take one file per request, or can it handle multiple files at once? There is not enough information in your question for us to help you, I'm afraid. Commented Jul 2, 2018 at 14:48
  • The back end is handling one file per request. How can i make it to handle multiple files at once? Commented Jul 3, 2018 at 5:32
  • That's hard to tell without seeing how your backend code handles the request, I'm afraid. Commented Jul 3, 2018 at 9:33

2 Answers 2

0

You could create a fetch for each element in your array, and put all the data in a FormData:

const promises = array1.map(obj => {
  const formData = new FormData();

  Object.keys(obj).forEach(key => {
    formData.append(key, obj[key]);
  });

  return fetch('/your-file-upload-endpoint', {
    method: 'POST',
    body: formData
  });
}

Promise.all(promises).then(() => {
  console.log('All files were uploaded');
}).catch(error => {
  console.error(error);
});
Sign up to request clarification or add additional context in comments.

3 Comments

@MeghaVerma Yes, but it's the image your want to upload, right? If that is not correct, you need to update your question with more information of what you backend expects to receive.
I am inserting/updating the table and so I need few values along with the image.
@MeghaVerma I updated the answer with a possible solution.
0

Did you try this?

array1.forEach(file => {
  formData.append("images[]", file.image, file.image.name)
})

Depends on your backend as well. How it receives the request ...

Comments

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.