How to upload image with optional data in multer?

File object sending from frontend using react and formData I have manually made the file object looks like...

Output of files enter image description here

After uploading a file i am getting the object in multer and express-upload

console.log(req.files.productImages)

[{
        "name": "galaxy-1.jpeg",
        "data": {
            "$binary": "/9j/4AAQSkZJRgABAQAAAQABAAD/2FasgasadagzxvADFCaBGRRXSADa0"
        },
        "size": 2895,
        "encoding": "7bit",
        "tempFilePath": "",
        "truncated": false,
        "mimetype": "image/jpeg",
        "md5": "b7192406a75b765dd0582daa4807ca71"
}]

I want to get file object with label: value.

example:

[{
        "label": "oxygen blue",
        "name": "galaxy-1.jpeg",
        "data": {
            "$binary": "/9j/4AAQSkZJRgABAQAAAQABAAD/2FasgasadagzxvADFCaBGRRXSADa0"
        },
        "size": 2895,
        "encoding": "7bit",
        "tempFilePath": "",
        "truncated": false,
        "mimetype": "image/jpeg",
        "md5": "b7192406a75b765dd0582daa4807ca71"
}]

Please help me to achieve this thing.


Solution 1:

Afaik this is not possible as multer will either receive the file itself without any additonal custom properties and/or any text-fields present in the form-data request. But ... multer allows you to access both files and text-fields.

So assuming your request looks something like this:

curl --location --request POST 'localhost:3000/test-upload' \
--form 'files=@"/path/to/file1"' \
--form 'label="custom-label-file1"' \
--form 'label="custom-label-file2"' \
--form 'files=@"/path/to/file2"'

and this server-side code:

app.post('/test', upload.array('files'), function (req, res, next) {
    console.log(req.files)
    console.log(req.body)
    res.send(...);
})

Then the following will be logged to the console:

Uploaded files:  [
  {
    fieldname: 'files',
    originalname: 'file1',
    encoding: '7bit',
    mimetype: 'text/plain',
    ...
  },
  {
    fieldname: 'files',
    originalname: 'file2',
    encoding: '7bit',
    mimetype: 'application/pdf',
    ...
  }
]
Uploaded text fields:  { label: [ 'custom-label-file1', 'custom-label-file2] }

According to this github-issue multer preserves the order, so you could use the corresponding index of the files to find their labels.