Skip to content
Advertisement

How to upload a file using the fetch API in Javascript to a Laravel Controller?

I have a FILES variable that looks like this:

Output Example

I am trying to receive these files at my Laravel controller like so:

JavaScript

I am posting to this endpoint using the fetch API like so:

JavaScript

In my response (network tab) I get:

JavaScript

I tried to JSON.Stringify(FILES) and got:

JavaScript

Can anyone point me in the right direction to why the file is not posted? This is how the FILES is created.

JavaScript

Advertisement

Answer

You need to append files to your FormData object, not a plain object.

i.e. given formData.append("key", value), the value needs to be a file object (it can also be a string). It can’t be a plain object (like FILES in your example) as that will be converted to a string, which isn’t useful:

JavaScript

Manually extracting the files from a file input and appending them one-by-one is overly complex though. Typically you would just use a form instead of appending to the FormData object:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement