Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: TinyMCE Upload Images

I want to upload images insinde the TinyMCE editor. I found instructions for that in the docs.

These are my Javascript settings:

tinymce.init({ 
       selector: '#about',          
       images_upload_url: '/home/profile/about/img',
     });

tinymce.activeEditor.uploadImages(function(success) {
      $.post('/home/profile/about/img', tinymce.activeEditor.getContent()).done(function() {
        console.log("Uploaded images and posted content as an ajax request.");
      });
    });

I created the following route to check if everything is setup correctly

Route::post('/home/profile/about/img', function(){
 return json_encode(['location' => '/storage/app/public/pictures/bestAvatar.png' ]);
});

I expected that when I upload an image nothing will be uploaded and the image bestAvatar.png is shown - however instead I get an error:

enter image description here

Am I missing anything? Is it maybe because there is no default csrf token in the tinymce ajax call?

like image 807
Adam Avatar asked Mar 05 '18 23:03

Adam


3 Answers

This is how I solved it:

tinymce.init({ 
       selector: '#about',          
       images_upload_handler: function (blobInfo, success, failure) {
           var xhr, formData;
           xhr = new XMLHttpRequest();
           xhr.withCredentials = false;
           xhr.open('POST', '/home/profile/about/img');
           var token = '{{ csrf_token() }}';
           xhr.setRequestHeader("X-CSRF-Token", token);
           xhr.onload = function() {
               var json;
               if (xhr.status != 200) {
                   failure('HTTP Error: ' + xhr.status);
                   return;
               }
               json = JSON.parse(xhr.responseText);

               if (!json || typeof json.location != 'string') {
                   failure('Invalid JSON: ' + xhr.responseText);
                   return;
               }
               success(json.location);
           };
           formData = new FormData();
           formData.append('file', blobInfo.blob(), blobInfo.filename());
           xhr.send(formData);
       }
     });
like image 175
Adam Avatar answered Oct 05 '22 04:10

Adam


In general 419 error is csrf token error which means you need to add

protected $except = [
    //
    '/upload',
];

in your VerifyCsrToken.php file.

Follow the link to get more understanding About TinyMCE 419 Error in Laravel

I experienced the same problem. Check it out in my website how to solve this problem.

like image 22
Dastagir Ahmed Avatar answered Oct 05 '22 04:10

Dastagir Ahmed


Yes, you have a right. Try to add:

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

to the ajax header

like image 23
Piotr P. Avatar answered Oct 05 '22 02:10

Piotr P.