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?
