mardi 20 avril 2021

Upload Image In Laravel With jQuery AJAX

I am trying to upload photo in Laravel using jQuery AJAX. But it's always failed many times with error message

The photo must be an image. The photo must be a file of type: jpeg, png, jpg, gif, svg.

I have no idea why. What's wrong with my code below?

Controller

$validator = \Validator::make($request->all(), [
        'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);
    
    if ($files = $request->file('image')) {
            //insert new file
            $destinationPath = 'public/product_images/'; // upload path
            $image_path = date('YmdHis') . "." . $files->getClientOriginalExtension();
            $files->move($destinationPath, $image_path);
        }

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

View

    $("#photo").fileinput({
        theme: 'fa',
        uploadUrl: '',
        uploadExtraData: function() {
            return {
                _token: $("input[name='_token']").val(),
            };
        },
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        overwriteInitial: false,
        maxFileSize: 2000,
        maxFilesNum: 5,
        slugCallback: function(filename) {
            return filename.replace('(', '_').replace(']', '_');
        }
    });
                        
    $('#saveBtnForCreate').click(function(e) {
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            url: "",
            method: 'post',
            enctype: 'multipart/form-data',
            cache: false,
            dataType: 'JSON',
            data: {
                photo: $('#photo').val()
            },
            success: function(result) {
                if (result.errors) {
                    $('.alert-danger').html(
                        'An error in your input!'
                    );
                    $.each(result.errors, function(key, value) {
                        $('.alert-danger').show();
                        $('.alert-danger').append('<strong><li>' + value +
                            '</li></strong>');
                    });
                } 
            }
        });
    });


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/32tbKl8
via IFTTT

1 commentaire:

  1. How To Upload Image Using Ajax In Laravel

    We can upload image using ajax with Json response. Here, you can see ,we make script in laravel using ajax and make image upload to the folder without refreshing a page..

    For More Info:- How To Upload Image Using Ajax In Laravel

    RépondreSupprimer