Search code examples
javascriptphpreact-nativeaxiosform-data

Unclear Behaviour of FormData: Sending an Array of Files to API


I'm writing a react native app where I'm supposed to send an array of files to an endpoint.

As per the FormData.append MDN docs:

As with regular form data, you can append multiple values with the same name. ... This technique makes it simpler to process multi-file uploads because the resultant data structure is more conducive to looping.

Hence, my code:

data.append('file', document);
// document is a document picker object
// {"size":...,"name":"...","uri":"...","type":"..."}

On sending the request, I get a 500 response with this error:

Cannot use object of type Illuminate\Http\UploadedFile as array

In plain English, the endpoint was expecting an array but it got a UploadedFile. Isn't FormData supposed to send an array?

What's the error in my code? If you need more code snippets, please, request.


Solution

  • From the error message, it sounds like your server-side technology is PHP. If so, you can tell PHP that file is an array by adding [] after it, e.g.:

    data.append('file[]', document);
    // −−−−−−−−−−−−−−^^