How to upload image file with additional information like label or alt value in express-fileupload?
I am trying to add a label text in file object but when uploading in node.js through express-fileupload. Its uploading the file but label is missing.
const [files, setFiles] = useState([]);
const imageLabelChanger = (index, e) => {
const value = e.target.value;
//insert label and value for specifix image by index
files[index].file.label = value;
setFiles(files);
};
const FD = new FormData();
const createProduct = (e) => {
e.preventDefault();
for (let i in files) {
FD.append("productImageArray", files[i].file);
}
dispatch(addProductImage(paramId, FD));
};
With this code i am getting the files object
console.log(files)
output: [
{
"id": 7,
valid: true,
"file": File{
label: "oxygen blue",
lastModified: 1642222607314,
lastModifiedDate: Sat Jan 15 2022 10:26:47 GMT+0530 (India Standard Time) {},
name: "galaxy-8.jpeg",
size: 8433,
type: "image/jpeg",
},
{
"id": 8,
valid: true,
"file": File{
lastModified: 1642222607314,
lastModifiedDate: Sat Jan 15 2022 10: 26: 47 GMT+0530(India Standard Time) {},
name: "galaxy-9.jpeg",
size: 9458,
type: "image/jpeg",
}
]
After file upload i am getting file object but not getting the actual files object what i was send using formData,label key and its value is missing
console.log(req.files.productImages)
output: [
{
lastModified: 1642222607314,
lastModifiedDate: Sat Jan 15 2022 10:26:47 GMT+0530 (India Standard Time) {},
name: "galaxy-8.jpeg",
size: 8433,
type: "image/jpeg",
data:
Binary('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7...', 0)
},
{
lastModified: 1642222607314,
lastModifiedDate: Sat Jan 15 2022 10: 26: 47 GMT+0530(India Standard Time) {},
name: "galaxy-9.jpeg",
size: 9458,
type: "image/jpeg",
data:
Binary('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7...', 0)
}
]
Please help me how can i make that things i think this problem is with req.files may be it doesn't take any extra property so if there has any way to achieve this.
Advance Thank you
Solution 1:
I a, not sure if this is applicable to your situation but I usually attach a 'body' object with the additional details when sending files. Something like this:
const [files, setFiles] = useState([]);
const imageLabelChanger = (index, e) => {
const value = e.target.value;
//insert label and value for specifix image by index
files[index].file.label = value;
setFiles(files);
};
const FD = new FormData();
const createProduct = (e) => {
e.preventDefault();
for (let i in files) {
FD.append("productImageArray", files[i].file);
FD.append("productImageArrayLabels", files[i].file.label); // Add another property to the formData here
}
dispatch(addProductImage(paramId, FD));
};
That way you'd have a files object and a body object on the server:
- Files: productImageArray
- File Labels: productImageArrayLabels