从本地上传图像到tinyMCE

21

tinyMCE提供了一个插入图像的按钮,但如何处理其功能,请提供一些代码。


2
您需要购买imagemanager组件才能启用此功能。 - Lazarus
8个回答

28

我已经给@pavanastechie写的代码点了赞,但最终我对它进行了大量重写。这里是一个更短的版本,可能对某些人有价值。

    tinymce.init({
        toolbar : "imageupload",
        setup: function(editor) {
            var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
            $(editor.getElement()).parent().append(inp);

            inp.on("change",function(){
                var input = inp.get(0);
                var file = input.files[0];
                var fr = new FileReader();
                fr.onload = function() {
                    var img = new Image();
                    img.src = fr.result;
                    editor.insertContent('<img src="'+img.src+'"/>');
                    inp.val('');
                }
                fr.readAsDataURL(file);
            });

            editor.addButton( 'imageupload', {
                text:"IMAGE",
                icon: false,
                onclick: function(e) {
                    inp.trigger('click');
                }
            });
        }
    });

注意:这依赖于 jQuery,并且没有它将无法工作。此外,它假定浏览器支持 window.FileReader,并且不会检查它。


感谢您发布这篇文章,帮助了我很多! - stephen.hanson
1
如果您使用此代码,则承诺图像嵌入在HTML中,而不是作为单独的文件存储在文件系统中。这是原始问题(“从本地上传图像到tinyMCE”)的解决方案。如果您有其他问题,则可能需要不同的解决方案。 - Chris Lear
2
TinyMCE已经具备类似的功能:https://www.tinymce.com/docs/get-started/upload-images/ - jayarjo
脚本很好用,除了为什么你清空了inp.val()?我通过删除它来实现上传。现在我正在基于你的脚本工作,实现多文件上传。 - Michael Eugene Yuen
编辑模式下大小超过200KB的图片无法正常工作!!有没有解决办法? - Vivek Parmar
显示剩余3条评论

15

我使用了pavanastechie和Chris Lear的解决方案,这对我非常有效,并想分享一个完整的示例,基于他们的解决方案,将图像上传到服务器并使用服务器返回的URL嵌入图像:

tinymce.init({
  toolbar: 'imageupload',
  setup: function(editor) {
    initImageUpload(editor);
  }
});

function initImageUpload(editor) {
  // create input and insert in the DOM
  var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
  $(editor.getElement()).parent().append(inp);

  // add the image upload button to the editor toolbar
  editor.addButton('imageupload', {
    text: '',
    icon: 'image',
    onclick: function(e) { // when toolbar button is clicked, open file select modal
      inp.trigger('click');
    }
  });

  // when a file is selected, upload it to the server
  inp.on("change", function(e){
    uploadFile($(this), editor);
  });
}

function uploadFile(inp, editor) {
  var input = inp.get(0);
  var data = new FormData();
  data.append('image[file]', input.files[0]);

  $.ajax({
    url: '/admin/images',
    type: 'POST',
    data: data,
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR) {
      editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
    },
    error: function(jqXHR, textStatus, errorThrown) {
      if(jqXHR.responseText) {
        errors = JSON.parse(jqXHR.responseText).errors
        alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
      }
    }
  });
}

11

!!!!ENJOY!!! 这里提供了从本地计算机直接加载的解决方案

JSFIDDLE DEMO

<textarea name="content"></textarea> <title>在tinymce中加载本地图片</title> <br/> <b>图片大小应小于500kb</b>

JAVA SCRIPT代码

`

tinymce.init({
    selector: "textarea",
    toolbar: "mybutton",
    setup: function(editor) {
        editor.addButton('mybutton', {
            text:"IMAGE",
            icon: false,
            onclick: function(e) {
                console.log($(e.target));
                if($(e.target).prop("tagName") == 'BUTTON'){
                    console.log($(e.target).parent().parent().find('input').attr('id'));
                    if($(e.target).parent().parent().find('input').attr('id') != 'tinymce-uploader') {
                        $(e.target).parent().parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
                    }
                    $('#tinymce-uploader').trigger('click');
                    $('#tinymce-uploader').change(function(){
                        var input, file, fr, img;

                        if (typeof window.FileReader !== 'function') {
                            write("The file API isn't supported on this browser yet.");
                            return;
                        }

                        input = document.getElementById('tinymce-uploader');
                        if (!input) {
                            write("Um, couldn't find the imgfile element.");
                        } else if (!input.files) {
                            write("This browser doesn't seem to support the `files` property of file inputs.");
                        } else if (!input.files[0]) {
                            write("Please select a file before clicking 'Load'");
                        } else {
                            file = input.files[0];
                            fr = new FileReader();
                            fr.onload = createImage;
                            fr.readAsDataURL(file);
                        }

                        function createImage() {
                            img = new Image();
                            img.src = fr.result;
                            editor.insertContent('<img src="'+img.src+'"/>');
                        }
                    });

                }

                if($(e.target).prop("tagName") == 'DIV'){
                    if($(e.target).parent().find('input').attr('id') != 'tinymce-uploader') {
                        console.log($(e.target).parent().find('input').attr('id'));                                
                        $(e.target).parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
                    }
                    $('#tinymce-uploader').trigger('click');
                    $('#tinymce-uploader').change(function(){
                        var input, file, fr, img;

                        if (typeof window.FileReader !== 'function') {
                            write("The file API isn't supported on this browser yet.");
                            return;
                        }

                        input = document.getElementById('tinymce-uploader');
                        if (!input) {
                            write("Um, couldn't find the imgfile element.");
                        } else if (!input.files) {
                            write("This browser doesn't seem to support the `files` property of file inputs.");
                        } else if (!input.files[0]) {
                            write("Please select a file before clicking 'Load'");
                        } else {
                            file = input.files[0];
                            fr = new FileReader();
                            fr.onload = createImage;
                            fr.readAsDataURL(file);
                        }

                        function createImage() {
                            img = new Image();
                            img.src = fr.result;
                             editor.insertContent('<img src="'+img.src+'"/>');
                        }
                    });
                }

                if($(e.target).prop("tagName") == 'I'){
                    console.log($(e.target).parent().parent().parent().find('input').attr('id')); if($(e.target).parent().parent().parent().find('input').attr('id') != 'tinymce-uploader') {               $(e.target).parent().parent().parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
                                                                                           }
                    $('#tinymce-uploader').trigger('click');
                    $('#tinymce-uploader').change(function(){
                        var input, file, fr, img;

                        if (typeof window.FileReader !== 'function') {
                            write("The file API isn't supported on this browser yet.");
                            return;
                        }

                        input = document.getElementById('tinymce-uploader');
                        if (!input) {
                            write("Um, couldn't find the imgfile element.");
                        } else if (!input.files) {
                            write("This browser doesn't seem to support the `files` property of file inputs.");
                        } else if (!input.files[0]) {
                            write("Please select a file before clicking 'Load'");
                        } else {
                            file = input.files[0];
                            fr = new FileReader();
                            fr.onload = createImage;
                            fr.readAsDataURL(file);
                        }

                        function createImage() {
                            img = new Image();
                            img.src = fr.result;
                             editor.insertContent('<img src="'+img.src+'"/>');
                        }
                    });
                }

            }
        });
    }
});

`


当我在本地机器上尝试这个时,我需要点击文本“image”之外但在按钮内部,这样搜索才能起作用。为什么呢? - Rey Norbert Besmonte

5
我还没有尝试过iManager,但发现TinyFCK很好用且易于配置,它可以将CKEditor的文件管理器与TinyMCE集成。
1. 下载TinyFCK
2. 用 CKEditor 的 filemanager 文件夹替换 TinyFCK 中的 filemanager 文件夹。
3. 代码:
tinyMCE.init({
     theme : "advanced",
     file_browser_callback : "fileBrowserCallBack",
});
function fileBrowserCallBack(field_name, url, type, win) {
     var connector = "../../filemanager/browser.html?Connector=connectors/php/connector.php";
     var enableAutoTypeSelection = true;
     var cType;
     tinyfck_field = field_name;
     tinyfck = win;
     switch (type) {
         case "image":
             cType = "Image";
         break;
         case "flash":
             cType = "Flash";
         break;
         case "file":
             cType = "File";
         break;
     }
     if (enableAutoTypeSelection && cType) {
         connector += "?Type=" + cType;
     }
     window.open(connector, "tinyfck", "modal,width=600,height=400");
  }

4

你好,能提供一些例子吗?我在使用这个插件时遇到了错误:“存在错误!根文件夹不存在。” :( - dmh
@dmh 创建 /var/ww/html/tinymce/source 文件夹并授予 Apache 写入权限。 - Dilawar

1

我知道这是一个老问题。然而,我认为这个答案可能会帮助想要使用tinyMCE 5.xx上传多个图像的人。 基于@Chris Lear和@stephen.hanson的答案,我修改了一些代码来支持多个图像上传。以下是我的代码。希望它能帮助到某些人。

tinymce.init({
toolbar: 'imageupload',
setup: function(editor) {
  initImageUpload(editor);
  }
});

function initImageUpload(editor) {
// create input and insert in the DOM
 var inp = $(`<input id='tinymce-uploader' type='file' name='pic' accept='image/*' style='display:none' multiple>`);
  $(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
  editor.addButton('imageupload', {
  text:'IMAGE',
  onAction: function(_) { 
 // when toolbar button is clicked, open file select modal
    inp.trigger('click');
  }
});
 // when a file is selected, upload it to the server
inp.on('change',function(){
    for(let i=0;i<inp[0].files.length;i++){
        let file = inp[0].files[i];
        let data = new FormData();
        data.append('multipartFile',file);
        axios.post('/upload/image/url',
        data,
        {
         headers: {
          'Content-Type': 'multipart/form-data'
          }
         }).then(res => {
          if (res.status = 200) { 
              editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
             // clear data to avoid uploading same data not working in the second time
             inp.val('');
          }
      })
  }

1

根据@Chris Lear的答案,我重新修改了脚本,以支持将多个文件上传到服务器,并使用一个小的php脚本在内容发布后和表格更新之前删除了预览的数据图片。

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('<input id="tinymce-uploader_'+n+'" class="tinymce-uploader" type="file" name="pic['+n+']" mutliple accept="image/*" style="display: none;">');
                            $('#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('<img data-name="'+filename+'" src="'+img.src+'"/>');
                                    }
                                    fr.readAsDataURL(file);
                            });
                        }
                });
        },

在PHP端的上传PHP文件内部:
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;        
    }

0

它适用于图像上传。文件上传是否也可行?我想添加一个自定义文件上传选项,从本地上传到tinyMCE,并希望通过URL显示它。

 Code is something like below which not working:


   ed.addButton('mybutton2', {
        text:"File",
        icon: false,

        onclick: function(e) {
            console.log($(e.target));
            if($(e.target).prop("tagName") == 'BUTTON'){
                console.log($(e.target).parent().parent().find('input').attr('id'));
                if($(e.target).parent().parent().find('input').attr('id') != 
'tinymce-uploader') {
                    $(e.target).parent().parent().append('<input id="tinymce- 
uploader" type="file" name="pic" accept="*" height="100" weidth="100" 
 style="display:none">');
                }
                $('#tinymce-uploader').trigger('click');
                $('#tinymce-uploader').change(function(){
                    var input, file, fr, img;

                    if (typeof window.FileReader !== 'function') {
                        write("The file API isn't supported on this browser yet.");
                        return;
                    }

                    input = document.getElementById('tinymce-uploader');
                           // var URL = document.my_form.my_field.value;
       alert(input.files[0]);
                    if (!input) {
                        write("Um, couldn't find the imgfile element.");
                    } else if (!input.files) {
                        write("This browser doesn't seem to support the `files` 
              property of file inputs.");

                    } else if (!input.files[0]) {
                        write("Please select a file before clicking 'Load'");
                       alert( input.files[0]);
                    } else {
                        file = input.files[0];
                        fr = new FileReader();
                        fr.onload = createFile;
                        fr.readAsDataURL(file);
                            //  alert(fr.result);

                    }

                    function createFile() {
                       //what should I write here?
                      ed.insertContent('<a href="'+img.src+'">download 
      file_name</a>');
                    }
                });

            }







        }
    });

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