Html 从本地上传图像到 tinyMCE

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3872009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:46:08  来源:igfitidea点击:

upload image from local into tinyMCE

htmltinymce

提问by Iphone_bharat

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

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

采纳答案by Iphone_bharat

Din't try iManager but found tinyFCK good and easy to configure which gives CKEditor's filemanager integrated with TinyMCE

不要尝试 iManager 但发现 tinyFCK 很好且易于配置,这使 CKEditor 的文件管理器与 TinyMCE 集成

1.Download TinyFCK

1.下载TinyFCK

2.replace filemanger folder in tinyFCK with filemanager folder of ur CKEditor

2.用你的CKEditor的文件管理器文件夹替换tinyFCK中的文件管理器文件夹

3.code :

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

回答by Chris Lear

I have upvoted the code written by @pavanastechie, but I ended up rewriting it quite a lot. Here's a version that is far shorter, which might have value to some people

我已经对@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');
                }
            });
        }
    });

NOTE: this relies on jquery, and won't work without it. Also, it assumes that the browser supports window.FileReader, and doesn't check for it.

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

回答by stephen.hanson

I used pavanastechie's and Chris Lear's solutions, which worked perfectly for me, and wanted to share a complete example built on theirs that uploads the image to the server and embeds the image using the URL provided back by the server:

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

回答by PavanAsTechie

!!!!ENJOY!!!here is the solution to load directly from local computer

!!!!请享用!!!这是直接从本地计算机加载的解决方案

JSFIDDLE DEMO

JSFIDDLE 演示

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

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

JAVA SCRIPT CODE

爪哇脚本代码

`

`

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

            }
        });
    }
});

`

`

回答by despina

I know this post is old, but maybe this will help someone trying to find a open source file manager for tinymce:

我知道这篇文章很旧,但也许这会帮助那些试图为 tinymce 寻找开源文件管理器的人:

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

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

This worked great for me.

这对我很有用。

回答by Michael Eugene Yuen

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

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

And on php side inside the upload php 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;        
    }

回答by Shamsun Nahar

It works for image upload.Is this possible for file upload ? I want to add a custom file upload option from local into tinyMCE and want to show it by url .

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

            }







        }
    });