Friday, 3 January 2020

How to send a file in array of object to express server?

I have an array of the object, each object contains some properties of type string and a file.

This is how my array looks like:

const args = [
    {
        name: 'presentation',
        price: 9.99,
        tags: 'invest, finance, business',
        file: File,
        thumbnail: File
    },
    {
        name: 'presentation2',
        price: 20.99,
        tags: 'invest, finance, business',
        file: File,
        thumbnail: File
    }
]

const headers = {
 headers: {
   Authorization: `Bearer ${token}`
 }
};

My goal is to send this whole array of the object to the Express Server. there I will save information to the Mongo and upload the file to S3. But Currently, I am unable to get the file stream on the server when I send this in a POST request, even the whole req.body is an empty object when I console.log it

axios.post(`${slidesRoute}/createSlides`, args, headers);

Alternatively, I tried to put everything into FormData. for example:

let formData = new FormData();
    selectedFiles.forEach((selectedFile, i) => {
        formData.append(`name_${i}`, selectedFile.name);
        formData.append(`price_${i}`, selectedFile.price);
        formData.append(`tags_${i}`, selectedFile.tags);
        formData.append(`file_${i}`, selectedFile.file);
        formData.append(`thumbnail_${i}`, selectedFile.thumbnail);
    });
axios.post(`${slidesRoute}/createSlides`, formData, headers);

Then In the backend. I am unable to catch these files using multer. Because the filenames in form data are being generated dynamically like

file_1, file_2 file_3,...

But multer expects the exact filename to be passed for example multer().array('file')

so in my second approach I am unable to catch files using Multer



from How to send a file in array of object to express server?

No comments:

Post a Comment