Sending multipart form to backend service with multiple rows of data

Viewed 33

I'm trying out a bulk upload functionality where I can get user details like name, email, and profile pic (file) as fields. Upon submitting, they are sent directly to backend models and stored.

I was able to successfully send just one row of data by using Form Data object and appending all the fields including image file field. The issue comes when the uploaded data is more than 1 row. I'm not able to figure out how to send Form Data as array of objects to my backend.

I tried appending formdata to array. So something like

    //  Convert this 
    //  [
    //   { name: 'xyz', email: 'xyz@gmai.com', img_name: 'xyz' }, 
    //   { name: 'abc', email: 'abc@gmail.com', img_name: 'abc' }
    //  ]
    //
    //  to 
    //
    //  [
    //   { name: 'xyz', email: 'xyz@gmai.com', image: BinaryFile }, 
    //   { name: 'abc', email: 'abc@gmail.com', image: BinaryFile }
    //  ]
    const newDataToSend = []

    // append image file to appropriate row according to name
    if (imageFiles && imageFiles.length > 0) {
      dataToSend.forEach(row => {
        const formData = new FormData();
        Object.keys(row).forEach(column => {
          if (column === "img_name") {
            let fileObj;
            for (let i = 0; i < imageFiles.length; i++) {
              const file = imageFiles.item(i);
              if (file && file.name.indexOf(row[column]) > -1) {
                fileObj = file;
              }
            }
            if (fileObj) {
              formData.append("photo", fileObj);
            }
          } else {
            formData.append(column, row[column]);
          }
        });
        newDataToSend.push(formData);
      });
    }

This does not work. Throws error code 415 and payload is empty as well.

Are there any other solutions I can try?

3 Answers

could you please add the other codes you have written . possibly you may not have a submit button .

You could do JSON.stringify on the array data like shown in the code snippet:

let formdata = new FormData();
let dataArr = [data1, data2, data3];
formdata.append('dataArr', JSON.stringify(dataArr));

If you have the data in the form of an array of objects, you probably want to do something like this.

const dataToSend = [
  { firstName: 'Robin', lastName: 'Hood'}, 
  { firstName: 'Kavita', lastName: 'Gurav'}, 
  { firstName: 'Albert', lastName: 'Einstein'}
];


/** sending the data by the name 'data' */ 
const formData = new FormData();
formData.append('data', dataToSend);

fetch(<api endpoint>, {
    method: 'POST',
    body: formData
});

The backend now should be able to read the data submitted from data.

I tried this on my browser, the payload being sent is like below.

enter image description here

Related