mercredi 27 avril 2016

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="">
    <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);
    }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire