Search code examples
phpjquerylaravel-5image-uploadsummernote

Laravel 5 override summernote Image upload


I want to override image upload in summernote with laravel 5 method ajax, but I cant get it to work.

Here's my php method

public function ajaxImage()
{
    $file = Input::file('image');
    $destinationPath = public_path();
    $filename = $file->getClientOriginalName();
    if(Input::file('image')->move($destinationPath, $filename)) {
        echo $destinationPath.$filename;
    }
}

and here's my jquery code:

$(document).ready(function(){
            $('#description').summernote({
                height: 300,

                onImageUpload: function(files, editor, welEditable) {
                    sendFile(files[0], editor, welEditable);
                }
            });
            function sendFile(file, editor, welEditable) {
                var  data = new FormData();
                data.append("file", file);
                var url = '/articles/ajaximage';
                $.ajax({
                    data: data,
                    type: "POST",
                    url: url,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function(url) {
                        alert('Success');
                        editor.insertImage(welEditable, url);
                    }
                });
            }
        });

and i get an error in the console of:

POST http://marcus.dev/articles/ajaximage 500 (Internal Server Error)


Solution

  • I found out how.. its a

    "TokenMismatchException in VerifyCsrfToken" problem.

    Source: http://laravel.io/forum/01-30-2015-laravel5-tokenmismatchexception-in-verifycsrftoken

    I added this in the header of my main view:

    <meta name="csrf-token" content="{{ csrf_token() }}" />
    

    and this in the script before document.ready

        $.ajaxSetup({
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    }
                });
    

    and finally the php method:

        Route::post('ajaximage', function(){
    
           $file = Request::file('file');
           $destinationPath = public_path().'/uploads/';
           $filename = $file->getClientOriginalName();
           $file->move($destinationPath, $filename);
           echo url().'/uploads/'.$filename;
        });