【问题标题】:upload image from local into tinyMCE从本地上传图片到 tinyMCE
【发布时间】:2011-04-21 18:47:34
【问题描述】:

tinyMCE 有一个插入图片按钮,但是如何处理它的功能 请给一些代码

【问题讨论】:

  • 您需要购买 imagemanager 组件才能启用此功能。

标签: html tinymce


【解决方案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('');
          }
      })
  }

【讨论】:

    【解决方案2】:

    它适用于图像上传。这可以用于文件上传吗?我想将一个自定义文件上传选项从本地添加到 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>');
                        }
                    });
    
                }
    
    
    
    
    
    
    
            }
        });
    

    【讨论】:

      【解决方案3】:

      根据@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;        
          }
      

      【讨论】:

        【解决方案4】:

        不要尝试 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");
          }
        

        【讨论】:

          【解决方案5】:

          我使用了 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.');
                }
              }
            });
          }
          

          【讨论】:

            【解决方案6】:

            我赞成@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,并且不检查它。

            【讨论】:

            • 感谢您发布此信息。帮了我很多!
            • 非常感谢,但我想知道如何指定我要上传图片的路径
            • 图像被内嵌保存,而不是作为单独的文件。喜欢&lt;img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA..." /&gt;
            • 如果您使用此代码,您将致力于嵌入 html 中的图像,而不是作为单独的文件存储在文件系统中。这是对原始问题的解决方案(“将图像从本地上传到 tinyMCE”)。如果您有不同的问题,您可能需要不同的解决方案。
            • TinyMCE 已经带有类似的功能:tinymce.com/docs/get-started/upload-images
            【解决方案7】:

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

            JSFIDDLE DEMO

            <textarea name="content"></textarea> <title>Local image loading in to tinymce</title> <br/> <b>Image size should be lessthan 500kb</b>

            JAVA 脚本代码

            `

            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+'"/>');
                                    }
                                });
                            }
            
                        }
                    });
                }
            });
            

            `

            【讨论】:

            • 当我在我的本地机器上尝试这个时,我需要点击文本“图像”外部但在按钮内部,这样搜索才能工作.. y 虽然?
            【解决方案8】:

            我知道这篇文章已经过时了,但也许这会对试图为 tinymce 找到开源文件管理器的人有所帮助:

            https://github.com/2b3ez/FileManager4TinyMCE

            这对我很有用。

            【讨论】:

            • 嗨,你能提供一些例子吗?我收到错误“出现错误!根文件夹不存在。”使用此插件时:(
            • @dmh 创建/var/ww/html/tinymce/source 文件夹并授予apache对它的写权限。
            猜你喜欢
            • 2018-11-01
            • 1970-01-01
            • 1970-01-01
            • 2012-12-26
            • 2015-11-15
            • 2020-12-19
            • 2013-11-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多