php - TinyMCE 和 Laravel 5.3 TokenMismatchException

标签 php laravel-5 tinymce csrf tinymce-4

我正在尝试在服务器端使用 Laravel 5.3 实现 TinyMCE 图像上传:

这是我的 TinyMCE JS,目前在 Blade 模板中:

<script src="{{ URL::to("/tinymce/tinymce.min.js") }}"></script>
<script>
    tinymce.init({
        selector: 'textarea',
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media",
        relative_urls: false,

        image_title: true,

        automatic_uploads: true,

        images_upload_url: '/discussions/save_images/',

        file_picker_types: 'image',

        images_upload_credentials: true,

        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function() {
                var file = this.files[0];
                var id = 'blobid' + (new Date()).getTime();
                var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                var blobInfo = blobCache.create(id, file);
                blobCache.add(blobInfo);
                cb(blobInfo.blobUri(), { title: file.name });
            };
            input.click();
        }
    });
</script>

我处理 TinyMCE 发出的 POST 请求的路径:

Route::post("/discussions/save_images/", 'Discussion\DiscussionController@saveImages');

我处理每次上传的操作:

public function saveImages(Request $request) {
    $filename = sha1(uniqid()).'.'.request()->file("name")->getClientOriginalExtension();
    $request->file("name")->move('/images/discussions/', $filename);
    return json_encode(["location"=>"/images/discussions/".$filename]);
}

Laravel 抛出 TokenMismatchException。如何将 CSRF token 传递到 TinyMCE 发出的 POST 请求中?

我知道通常可以通过 {{ csrf_token }} 在模板中访问此 token ,但我不确定关于 TinyMCE 的正确配置。

最佳答案

使用 images_upload_handler 执行自定义处理程序并在请求 header 中设置 X-CSRF-Token 有效。下面是完整的 JS 代码最终的样子:

tinymce.init({
        plugins: [
            "advlist autolink lists link image charmap print preview hr anchor pagebreak",
            "searchreplace wordcount visualblocks visualchars code fullscreen",
            "insertdatetime media nonbreaking save table contextmenu directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        selector: 'textarea',
        images_upload_handler: function (blobInfo, success, failure) {
            var xhr, formData;
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '/discussions/save_images');
            var token = document.getElementById("_token").value;
            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);
        },
        file_picker_callback: function(cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');
            input.onchange = function() {
                var file = this.files[0];
                var id = 'blobid' + (new Date()).getTime();
                var blobCache = tinymce.activeEditor.editorUpload.blobCache;
                var blobInfo = blobCache.create(id, file);
                blobCache.add(blobInfo);
                cb(blobInfo.blobUri(), { title: file.name });
            };
            input.click();
        }
    });

关于php - TinyMCE 和 Laravel 5.3 TokenMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43728841/

相关文章:

php - 为什么用 PHP 加密的东西与用 Ruby 加密的相同字符串不匹配?

php - 如何将复选框添加到数据表以用于删除所选行?

php - 如何在 "OR LIKE"条件 Laravel 中使用 "AND"

javascript - Action 拒绝返回 bool 值

javascript - 在 TinyMCE 中获取所选图像的 src

php - 使用 PHP 从字符串或文件中提取多个电话号码

php - 如何限制用户访问特定页面? (Drupal、PHP、FileMaker Pro 10)

checkbox - 在 Laravel 中激活/停用多个客户端

javascript - tinymce,通过主窗口上的单击按钮从对话框中获取输入字段值

html - TinyMCE 在 Umbraco 中清理 HTML