dimanche 25 avril 2021

Cant Upload Multiple Images In Laravel jQuery AJAX

I've stuck many days when I am trying to upload image files. I can't upload multiple images files with code below:

Controller

if ($request->TotalImages > 0) {

            for ($x = 0; $x < $request->TotalImages; $x++) {

                if ($request->hasFile('images' . $x)) {
                    $file      = $request->file('images' . $x);

                    $path = $file->store('public/product_images/');
                    $name = $file->getClientOriginalName();

                    $insert[$x]['name'] = $name;
                    $insert[$x]['path'] = $path;
                }
            }
        }

        $productId = DB::table('products')->insertGetId(
            [
                'product_photo' => $insert
            ]
        );

View

<input id="images" name="images[]" type="file" multiple
                            class="form-control "
                            data-iconName="fa fa-upload" data-overwrite-initial="false">
                        <br>
var formData = new FormData();
let TotalImages = $('#images')[0].files.length; //Total Images
        let images = $('#images')[0];
        for (let i = 0; i < TotalImages; i++) {
            formData.append('images' + i, images.files[i]);
        }
        formData.append('TotalImages', TotalImages);

        $.ajax({
            url: "",
            method: 'post',
            enctype: 'multipart/form-data',
            cache: false,
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'JSON',
            async: true,
            headers: {
                'Content-Type': undefined,
            },
            xhr: function() {
                myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            
        }); //ajax

It always show me an error:

The images field is required.

But with single upload it works!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire