0

I'm trying to post multiple files from an input using fetch API but form data remains empty after appending

I looked at the answers here, here, here, here and here and tried them all to no avail

Am using the Laravel framework for the backend, here's my Blade view file

<meta name="csrf-token" content="{{ csrf_token() }}">
<input class="form-control" type="file" id="pro-image" name="image[]" multiple onchange="submit()">

<script>
    function submit() {
        var ins = document.getElementById('pro-image').files.length;
        var fd = new FormData();
        for (var x = 0; x < ins; x++) {
            fd.append("pro-image[]", document.getElementById('pro-image').files[x]);
        }
        console.log(fd);
        fetch('/', {
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]').content
            },
            method: 'POST',
            credentials: "same-origin",
            body: fd,
        });
    }
</script>

The console logs an empty form data object

enter image description here

And this is the code in the backend

Route::post('/', function () {
    dd(request()->all());
});

In which I consequently get an empty array

enter image description here

Really can't tell why this isn't working! Any idea as to what am doing wrong?

Salim Djerbouh
  • 10,719
  • 6
  • 29
  • 61

1 Answers1

2

Remove your Content-Type: application/json header, or set it to multipart/form-data instead.

Aken Roberts
  • 13,012
  • 3
  • 34
  • 40
  • 1
    Setting it to `multipart/form-data` didn't help, removing it entirely fixes the issue, thanks – Salim Djerbouh Oct 15 '19 at 19:38
  • The console still logs an empty FormData, any idea why? – Salim Djerbouh Oct 15 '19 at 19:39
  • 2
    @Saly3301 You cannot inspect FormData by console logging it directly. You can either console log a specific value with FormData.get('key-name') or by using FormData.entries() as per this example: https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries – M Polak Oct 15 '19 at 19:50