0
votes

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.

1
No, FormData is not supposed to send an array. FormData sends whatever you tell it to send. In this case you appear to have called append once, so it sent a single object. If you were to call append multiple times with the same name, it would send an array (technically, it would send multiple items with the same name, which most server-side frameworks will interpret as an array of array-like construct). - Heretic Monkey
When you say "the server," do you mean some kind of server component within your React Native application? Or are you sending this to some other server? If so, what is the tech stack for that server? - T.J. Crowder
How then can you send a singleton (to a non-phpbacled where you can't specify an array syntax in the variable name)? @HereticMonkey - Kingdom Coder
You're mixing your jargon up. Singleton is a pattern for object lifetime in memory and has nothing to do with how you serialize data. In any case, I've answered the question of how to send multiple items with the same name (and in fact it's described in the quote from MDN); you call append multiple times with the same name. Since it is not clear where the document object has multiple elements, that's the best I can say. - Heretic Monkey
A singleton, in this sense, is a single element array. I'm afraid you must have misunderstood my question. How do you send a single element array with FormData? Specifically, how do send it to backends built in other languages other than PHP that don't have the square brackets (as per arrayName[]) indicating that the value being received is an array? Is this clearer? - Kingdom Coder

1 Answers

0
votes

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);
// −−−−−−−−−−−−−−^^