使用 Laravel 的 TinyMCE 图像上传,没有文件管理器

TinyMCE Image Upload with Laravel, without File Manager

我正在使用 TinyMCE 作为富文本编辑器,当我点击 image/video 按钮时,我想将它上传到服务器,即 Laravel。所有在线指南都显示使用文件管理器,但我不想在两者之间使用文件管理器。我希望用户直接上传图片(使用 ajax?),这样图片就可以在编辑器中导入而无需刷新页面。

我不知道从哪里开始。有没有办法直接上传图片,让用户可以在编辑器中即时使用image/video?如果可以,有什么方法可以实现?

在 justboil.me 上查看 justboilme,这是我所知道的最好的在 tinymce

中包含图像的方法

使用 tinyMCE.get('editor1').getContent(); 获取tinymce插件的内容 所以你的脚本可能是这样的 其中 editor1 是您在

上初始化 tinymce 的文本区域的 ID
<script>
    var tinymce_content = tinyMCE.get('editor1').getContent()
    $.post('your_post_url',
    {
        content: tinymce_content
    },
    function(data)
    {
        //what to do when request is complete
    })
</script>

将此代码用于您的前端

<script>tinymce.init({

        selector:'textarea' ,
        height: 400,
        toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | fontsizeselect link image | media",
        images_upload_handler: function (blobInfo, success, failure) {
            var xhr, formData;
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', '/AdminPanel/UploadNewsPhoto');
            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);
        },
        directionality: 'rtl',

        plugins: 'image code , media',

        /* enable title field in the Image dialog*/
        image_title: true,
        /* enable automatic uploads of images represented by blob or data URIs*/
        automatic_uploads: true,
        /*
          URL of our upload handler (for more details check: https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_url)
          images_upload_url: 'postAcceptor.php',
          here we add custom filepicker only to Image dialog
        */
        file_picker_types: 'image',
        /* and here's our custom image picker*/
        file_picker_callback: function (cb, value, meta) {
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', 'image/*');

            /*
              Note: In modern browsers input[type="file"] is functional without
              even adding it to the DOM, but that might not be the case in some older
              or quirky browsers like IE, so you might want to add it to the DOM
              just in case, and visually hide it. And do not forget do remove it
              once you do not need it anymore.
            */

            input.onchange = function () {
                var file = this.files[0];

                var reader = new FileReader();
                reader.onload = function () {
                    /*
                      Note: Now we need to register the blob in TinyMCEs image blob
                      registry. In the next release this part hopefully won't be
                      necessary, as we are looking to handle it internally.
                    */
                    var id = 'blobid' + (new Date()).getTime();
                    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
                    var base64 = reader.result.split(',')[1];
                    var blobInfo = blobCache.create(id, file, base64);
                    blobCache.add(blobInfo);

                    /* call the callback and populate the Title field with the file name */
                    cb(blobInfo.blobUri(), { title: file.name });
                };
                reader.readAsDataURL(file);
            };

            input.click();
        }

});</script>

然后使用 laravel

实现您的上传
 public function UploadNewsPhoto(Request $request)
{

    $fileFormat = $request->file('file')->getClientOriginalExtension();

    $PhotoValidFormat = array('jpg', 'png', 'gif', 'jpeg', 'bmp');


    if (in_array(strtolower($fileFormat), $PhotoValidFormat) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {

        $PhotoName = uniqid() . '.' . $request->file('file')->getClientOriginalExtension();

        $fileSize = number_format($_FILES['file']['size'] / 1048576, 2);//to mb


        if ($fileSize <= 50) {


            if ($request->file('file')->move(base_path() . env('Photo_News_UPLOAD_PATH'), $PhotoName)) {

               return json_encode(array(

                   'location'=>'/posts/images/'.$PhotoName

               ));


            } else
                $res = -1;

        } //bad format or size not allowed for php.ini
        else {
            if (isset($_FILES['file']['error']) && $_FILES['file']['error'] == 1)
                $res = -1;
            else
                $res = 0;
        }

        echo json_encode(array('res' => $res));

    }


}

你必须return 'location'=>'/posts/images/'.$PhotoName