本文介绍了Laravel:TinyMCE上传图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在TinyMCE编辑器中上传图像.我在文档中 找到了说明.

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

这些是我的Javascript设置:

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' ]);
});

我希望在上传图片时不会上传任何内容,并且会显示图片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:

我错过了什么吗?可能是因为tinymce ajax调用中没有默认的csrf令牌吗?

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

推荐答案

这是我解决的方法:

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

这篇关于Laravel:TinyMCE上传图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:59