javascriptlaravelfetchform-datafilelist

How to post multiple files with fetch API?


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?


Solution

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