如何使用Asp.net MVC上传和注入图像到tinymce 4

时间:2015-11-09 20:02:17

标签: javascript asp.net-mvc tinymce-4

因为有绝对没有现代的方式将图片上传到 .net中免费,我想是想添加一个在html中输入文件,然后使用ajax将其上传到服务器,然后在tinymce编辑器中包含该文件。

问题在于注入图像,我不知道如何......

有什么办法吗?

5 个答案:

答案 0 :(得分:7)

我是在TinyMCE 4.3.10

中做到的

在tinymce.init中,添加以下选项:

public ActionResult UploadImage(HttpPostedFileBase file)
{
    file.SaveAs("<give it a name>");
    return Json(new { location = "<url to that file>" });
}

在CSharp代码中:

w[1,1,1,1,1]= 1)

您应该能够将图像复制并粘贴到textarea(奇怪的是,拖放不再起作用)。

答案 1 :(得分:6)

好的,Micro $ oft或其他人需要真正对此做些什么,同时这是调试时间的结果:

此解决方案使用直接上传功能(已经在Tinymce中,但默认情况下已禁用),并且通过一些jquery hack,我们将图像注入textarea。

注入图像后必须更改尺寸。在最近的Tinymce版本中,他们还添加了一些不错的图像编辑工具,也可以使用这种方法。

现在代码:

这是需要放在控制器中的动作:(注意路由)

public string Upload(HttpPostedFileBase file)
    {
        string path;
        string saveloc = "~/Images/";
        string relativeloc = "/Images/";
        string filename = file.FileName;

        if (file != null && file.ContentLength > 0 && file.IsImage())
        {
            try
            {
                path = Path.Combine(HttpContext.Server.MapPath(saveloc), Path.GetFileName(filename));
                file.SaveAs(path);
            }
            catch (Exception e)
            {
                return "<script>alert('Failed: " + e + "');</script>";
            }
        }
        else
        {
            return "<script>alert('Failed: Unkown Error. This form only accepts valid images.');</script>";
        }

        return "<script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('" + relativeloc + filename + "').closest('.mce-window').find('.mce-primary').click();</script>";
    }

这是Tinymce的完整代码,它将生成一个文本框和几个隐藏字段。它还会创建一个启用了一些插件的tinymce实例。

    <iframe id="form_target" name="form_target" style="display:none"></iframe>

<form id="my_form" action="/admin" target="form_target" method="post" enctype="multipart/form-data" style="width:0;height:0;overflow:hidden">
    <input name="file" type="file" onchange="$('#my_form').submit();this.value='';">
</form>
<script type="text/javascript">
tinymce.init({
    selector: "textarea",
    theme: "modern",
    plugins: [
        "advlist autolink lists link image charmap print preview hr anchor pagebreak",
        "searchreplace wordcount visualblocks visualchars code fullscreen",
        "insertdatetime media nonbreaking save table contextmenu directionality",
        "emoticons template paste textcolor colorpicker textpattern imagetools"
    ],
    toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image",
    toolbar2: "print preview media | forecolor backcolor emoticons | ltr rtl",
    image_advtab: true,
    templates: [
        {title: 'Test template 1', content: 'Test 1'},
        {title: 'Test template 2', content: 'Test 2'}
    ],
    file_browser_callback: function(field_name, url, type, win) {
    if(type=='image') $('#my_form input').click();
}
});
</script>

<textarea id="my_editor" class="mceEditor">This will be an editor.</textarea>

您需要在项目根目录中创建一个名为“Images”的文件夹,以便上传图像。你还需要Tinymce js文件和jquery。

根据您的设置更改表单的操作!!!

您也可以选择使用html助手。我不喜欢他们。但如果你愿意的话,请继续使用这些而不是这种手工制作的形式。

这个想法来自here,但它是在python中完成的,所以我重新编写它以使用ASP.NET MVC5和最新版本的TinyMCE。

我会在接下来的几天内继续研究这个问题,并在必要时编辑这个答案。

答案 2 :(得分:1)

这是我最新版本的tinymce的配置..

  

File_browser_callback已弃用

..它的工作原理..这适用于复制粘贴,插入图像。我还没有尝试使用文件上传管理器

         automatic_uploads: true, << auto run your upload script

         images_upload_url: 'ImageUpload', <<your upload, I'm using mvc and I'm routing to "ImageUpload"

        images_reuse_filename:true, << this is where the return json from your code i had a hard time finding this out.  

       file_picker_types: 'image', << type where the upload will appear images dialog,link or file

        //custom file 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];

            // 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 blobInfo = blobCache.create(id, file);
            blobCache.add(blobInfo);
            console.log(id);
            console.log(blobCache);
            // call the callback and populate the Title field with the file name
            cb(blobInfo.blobUri(), { title: file.name });
            console.log(meta.filetype);



        };

        input.click();


    },

答案 3 :(得分:1)

我在一个JSF / Java Web应用程序中工作,这个代码在 tynymce.init javascript下面对我来说很好。 图片保存在文本字段的中间(我想)。我想不需要附加代码

tinymce.init({
      selector: "textarea",
      browser_spellcheck: true,
      paste_data_images: true,
      plugins: [
        "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
        "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
        "table contextmenu directionality template textcolor paste fullpage textcolor colorpicker textpattern"
      ],

      toolbar1: "bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | formatselect fontselect fontsizeselect",
      toolbar2: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image code | insertdatetime preview | forecolor backcolor",
      toolbar3: "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft",

      menubar: false,
      image_advtab: true,
      toolbar_items_size: 'small',

      file_picker_callback: function(callback, value, meta) {
          if (meta.filetype == 'image') {
                var inputFile = document.createElement("INPUT");
                inputFile.setAttribute("type", "file");
                inputFile.setAttribute("style","display: none");
                inputFile.click();
                inputFile.addEventListener("change", function() {
                var file = this.files[0];
                var reader = new FileReader();
                reader.onload = function(e) {
                  callback(e.target.result, {
                    alt: ''
                  });
                };
                reader.readAsDataURL(file);
             });
          }
        },

      insertdatetime_dateformat: "%d/%m/%Y",
      insertdatetime_timeformat: "%H:%M:%S",
      language: 'pt_BR',
    });

答案 4 :(得分:0)

HTML

API_KEY-替换为tinymce 选择器-替换 “控制”区域中的MVC控制器

  <script src="https://cdn.tiny.cloud/1/API_KEY/tinymce/5/tinymce.min.js"></script>
    <script>
        tinymce.init({
            selector: '#Body',
            menubar: ' edit view insert format tools table',
            toolbar: 'undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist  | forecolor backcolor removeformat | emoticons | fullscreen  | image media  link | code',
            plugins: 'code importcss  searchreplace autolink   visualblocks visualchars fullscreen image link media   codesample table charmap hr  nonbreaking anchor toc insertdatetime advlist lists  wordcount   imagetools textpattern noneditable   charmap   quickbars  emoticons',
            contextmenu: "link image imagetools table",
            image_advtab: true,
            toolbar_sticky: true,
            images_upload_url: '/Control/Home/UploadImage',
            paste_data_images: true,
        });
    </script>

C#

namespace Project.Areas.Control.Controllers
{
    [Authorize(Roles = "admin")]
    public class HomeController : WebBaseController
    {

        [HttpPost]
        public JsonResult UploadImage(HttpPostedFileBase file)
        {
            var uploadsPath = HostingEnvironment.MapPath($"/uploads");
            var uploadsDir = new DirectoryInfo(uploadsPath);
            if (!uploadsDir.Exists)
                uploadsDir.Create();

            var imageRelativePath = $"/uploads/{DateTime.Now:yyyy-MM-dd_HH-mm-ss}.jpg";
            var imageAbsPath = HostingEnvironment.MapPath(imageRelativePath);
            var imageBytes = file.InputStream.ReadToEnd();
            System.IO.File.WriteAllBytes(imageAbsPath, imageBytes);
            return Json(new { location = imageRelativePath });
        }
.....

扩展方法

public static byte[] ReadToEnd(this Stream input)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                input.CopyTo(ms);
                return ms.ToArray();
            }
        }