簡體   English   中英

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

[英]How to upload and inject image to tinymce 4 using Asp.net MVC

因此,因為絕對沒有將圖像免費上傳到.net 中的tinymce 的現代方法,我在考慮可能在 html 中添加文件上傳輸入,然后使用 ajax 將其上傳到服務器,然后將文件包含在 tinymce 編輯器中。

問題是向tinymce注入圖像,我不知道如何...

有什么辦法嗎?

好的,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 助手。 我不喜歡他們。 但是,如果您願意,請繼續使用它們而不是這種手工制作的表格。

這個想法來自這里,但它是在 python 中完成的,所以我重寫了它以與 ASP.NET MVC5 和最新版本的 TinyMCE 一起使用。

我將在接下來的幾天內繼續研究這個問題,並在必要時編輯這個答案。

我在 TinyMCE 4.3.10 中做了這個

在 tinymce.init 中,放置以下選項:

paste_data_images: true,
images_upload_url: '/YourController/UploadImage',
images_upload_base_path: '/some/basepath'

在 CSharp 代碼中:

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

您應該能夠將圖像復制並粘貼到您的文本區域(奇怪,拖放不再起作用)。

這是我最新版本的 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();


    },

我在 JSF/Java Web 應用程序中工作, tynymce.init javascript bellow 中的這段代碼對我來說很好用。 圖片保存在文本字段的中間(我想)。 我想不需要額外的代碼

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',
    });

HTML

API_KEY - 替換為您的 tinymce Selector - 替換“控制”區域中的 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();
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM