使用Laravel进行TinyMCE图像上传,无需文件管理器

时间:2017-02-25 21:53:33

标签: php jquery laravel tinymce tinymce-4

我使用TinyMCE作为富文本编辑器,当我点击图像/视频按钮时,我想将它上传到服务器上,即Laravel。所有在线指南都使用文件管理器,但我不想在其间使用文件管理器。我希望用户直接上传图像(使用ajax?),以便在没有页面刷新的情况下在编辑器中导入图像。

我很困惑从哪里开始。有没有办法直接上传图像,以便用户可以立即在编辑器中使用图像/视频?如果是这样,那么实现这个目标的方法是什么?

3 个答案:

答案 0 :(得分:0)

在justboil.me上查看justboilme,这是我所知道的最好的包含图像的内容

答案 1 :(得分:0)

使用 tinyMCE.get('editor1').getContent(); 获取tinymce插件的内容 所以你的脚本可能是这样的 其中editor1是你在textarea上初始化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>

答案 2 :(得分:0)

将此代码用于您的前端

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

    }


}

您必须返回     'location'=>'/ posts / images /'.$ PhotoName