Laravel: TinyMCE上传图片

5

我希望在TinyMCE编辑器中上传图片。我在文档中找到了相应的说明

以下是我的Javascript设置:

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

我创建了以下路由来检查是否正确设置了所有内容。
Route::post('/home/profile/about/img', function(){
 return json_encode(['location' => '/storage/app/public/pictures/bestAvatar.png' ]);
});

我原以为上传图片时不会上传任何内容,而是显示图片bestAvatar.png,但实际上却产生了错误:

enter image description here

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


将您的路由添加到routes/api.php而不是web.php,您就不需要CSRF令牌。 - Svetoslav Stefanov
3个回答

7
这是我的解决方法:
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);
       }
     });

1
是的,你是有权利的。 尝试添加:

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

到ajax头部


1
一般来说,419错误是csrf令牌错误,这意味着您需要添加。
protected $except = [
    //
    '/upload',
];

在您的VerifyCsrToken.php文件中。

点击链接以获取更多理解: Laravel中TinyMCE 419错误的相关内容

我也遇到了同样的问题。请查看我的网站,了解如何解决此问题。


4
您似乎是链接文章的作者。如果链接到您自己的站点或内容(或您有关联的内容),则必须在答案中[披露您的隶属关系](/help/promotion),以便不被视为垃圾邮件。根据Stack Exchange政策,在用户名中具有相同文本作为URL或在个人资料中提及它不被视为足够的披露。 - cigien
好的,我明白了。我是新手,如何让它更有效呢? - Dastagir Ahmed
最起码,您需要披露关联关系。因此,您可以简单地添加“我是链接文章的作者”。一般来说,注意只有在与问题相关时才应添加链接。此外,您不应该经常链接到自己的文章;偶尔几次是可以的,但过于频繁是不允许的。 - cigien
好的。谢谢澄清。我明白了。 - Dastagir Ahmed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接