How to identify request.file() dynamically


#1

Hi, I have tested with postman file uploads (both single file and multiple files) to adonisjs server.
It worked fine on each case.
I wonder how to make generic case which accept both single and multiple files upload.

const pictures = request.file('pictures', {
  types: ['image'],
  size: '2mb'
})

Those lines returned pictures into File when I passed single file and returned pictures into FileJar when I passed multiple files.
How can I identify whether pictures is a single file or multiple files?

For now, I just need to pass extra data on my multipart/form-data fields on my client app.


#2

You can use one interface to handle both single and multiple file uploads.

This is how i handle it in my project.

Client-side:

HTML:

<input id="test" name="test" type="file" name="test-file" placeholder="Upload file..." onchange ="fileChangeEvent(event)"/>

JAVASCRIPT:

  - create an array

this.filesToUpload = [];
    - every time when you select a file - e.g fileChangeEvent
       this.filesToUpload[fileInputName] = fileInput.target.files[0];
    - on clicking upload button

const formData: any = new FormData();
// get the values from filesToUpload
// append them to the formdata
formData.append("myFiles[]", files[i], files[i]['name']);

SERVER SIDE:

 request.multipart.file('myFiles[]', 
                                        {
                                            types: ['filetype'],
                                            size: '5mb'
                                    }, 
                                    async (file) => {});

   NOTE: The above code is a sample snippet from my project and might need some updates to solve your issue. Scan through the code carefully and update it to work for your scenario.

#3

I followed your suggestion

const gambars = request.multipart.file('gambars[]', {
  types: ['image'],
  size: '2mb'
}, async (gambar) => {
  console.log('hello')
})
return response
  .status(200)
  .json({
    gambars
  })

This is Postman result

I think for now I just keep to upload a single picture since I also have not found how to send multiple picture from my Ionic client app

Anyway, thank you so much for your respond :smiley: