upload image from local into tinyMCE

后端 未结 8 810
小鲜肉
小鲜肉 2021-02-04 02:33

tinyMCE has an insert image button, but how to handle its functionality pls give some code

8条回答
  •  生来不讨喜
    2021-02-04 03:11

    Based on @Chris Lear's answer, I have re-modified the script so that it supports multiple file uploads to server, and removed the data image for preview after content is posted and before table is updated with a little php script

    tinymce.init({
            selector: 'textarea',
            setup: function(editor) {
                    var n = 0;
                    var form = $('#form_id'); // your form id
                    editor.addButton( 'imageupload', {
                            text:"IMAGE",
                            icon: false,
                            onclick: function(e) {
                                $(form).append('');
                                $('#tinymce-uploader_'+n).trigger('click');
                                n++;
                                $('.tinymce-uploader').on("change",function(){
                                        var input = $(this).get(0);
                                        var file = input.files[0];
                                        var filename = file.name;
                                        var fr = new FileReader();
                                        fr.onload = function() {
                                                var img = new Image();
                                                img.src = fr.result;
                                                editor.insertContent('');
                                        }
                                        fr.readAsDataURL(file);
                                });
                            }
                    });
            },
    

    And on php side inside the upload php file:

    function data2src($content, $img_path ='') {
            preg_match('/data\-name="([^"]+)/i',$content, $data_name);
            $tmp = preg_replace('/src=["]data([^"]+)["]/i', '', $content);
            $content = preg_replace('/data\-name\=\"/i', 'src="'.$img_path, $tmp);
            return $content;        
        }
    

提交回复
热议问题