How to use both id and name in multiple image upload?

<input class="form-control" type="file" id="pro-image" name="image[]" multiple>

When Id work Successfully this time Name does not catch image path.

That means empty Array.
But when remove Id just use name="image[]" successfully submit value.

1 answer

  • answered 2019-10-15 18:29 Saly 3301

    Assuming you have a form, you can submit the images via Ajax using the fetch API like so

    <form action="/" method="post" enctype="multipart/form-data">
        @csrf
        <input class="form-control" type="file" id="pro-image" name="image[]" multiple>
        <button type="submit">Submit</button>
    </form>
    
    <script>
        let form = document.forms[0];
        form.onsubmit = (event) => {
            event.preventDefault();
            fetch('/', {
                method: 'POST',
                credentials: "same-origin",
                body: new FormData(form),
            });
        }
    </script>
    

    And return the paths array for the images like so

    Route::post('/', function () {
        $images = request()->file('image');
        $paths = [];
        foreach ($images as $image) {
            $paths[] = $image->store('/public');
        }
        return $paths;
    });
    

    And without a form, listen to input change

    <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]);
            }
            fetch('/', {
                headers: {
                    "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>
    

    And access from backend

    Route::post('/', function () {
        $images = request()->file('pro-image');
        $paths = [];
        foreach ($images as $image) {
            $paths[] = $image->store('/public');
        }
        return $paths;
    });
    

    Now you can see paths of the stored images in public directory on the network tab of dev tools

    Hope this helps