简体   繁体   中英

Fail to upload image using Ajax on Laravel 5

I try on my laravel project to create a form that upload a image on the server using ajax but the request always failed, I try to do this is there any problem in code ?

html:

<form id="changeImage" enctype="multipart/form-data">
    <input type="hidden" name="_token" id="_token" value="{{csrf_token() }}">
    <center>
        <div class="form-group">
             <center><input type="file" name="image" accept="image/*"></center>
         <p class="help-block">Format: png, jpg et gif.</p>
        </div>
    </center>
    <button type="submit" class="btn btn-primary">Submit</button>
   </form>

Ajax:

$('input[name="image"]').change(function(event) {
        files = event.target.files;
    });
$('#changeImage').submit(function(event) {
    event.preventDefault();
    var _token= $('input[name="_token"]').val();
    var data = new FormData();
    data.append('_token',_token);
    $.each(files, function(k, v) {
        data.append('image',v);
    });

    $.ajax({
        url: '/profile/image',
        type: 'POST',
        data:data,
        processData: false,
        contentType: "multipart/form-data",
        success: function(data){
            console.log('done'+data);
        },
        async: false,
        error: function(data){
            console.log('No');
            var errors = data.responseJSON; 
            errorsHtml = '<div class="alert alert-danger"><ul>';
            $.each( errors , function( key, value ) {
                errorsHtml += '<li>' + value[key] + '</li>';
            });
            errorsHtml += '</ul></div>';
            $( '#form-errors' ).html( errorsHtml );
        }
    });
});

Server Side - PHP (laravel):

Route:

Route::post('profile/image','ProfileFormsController@postImage');

Controller

public function postImage(Request $request){
    if($request->ajax()){
        $imagedestination = 'images\profile';
        $file = $request->file('image');
        $image_name = time()."-".$file->getClientOriginalName();
        $file->move($imagedestination, $image_name);
    }
}

You forgot about CSRF validation.

As far as this request is POST, you have to send also CSRF token, or, at least, disable check for this route.

Go to app/Http/Middleware/VerifyCsrfToken.php

and add your POST-url to protected $except = [];

Also read this part of documentation: https://laravel.com/docs/master/routing#csrf-protection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM