TinyMCE Editor Picture Upload Extension (base64), asp.net mvc5

Keywords: ASP.NET encoding Attribute

Editors usually upload pictures to the server first. If the user cancels or forgets to submit the form, it will produce a scrap map in the space, which will take up a lot of space in a long time. Now try to use base64 before submitting, and then process the < img > label src in the editor's content in the background. base64 images (saved as picture files and returned relative address strings to replace the original base64 encoding images) passed the test in the new TinyMCE editor (Version: 5.0.12 (2019-07-18). The browser is chrome

Code:

           tinymce.init({
                selector: 'textarea#Content',
                plugins: 'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help paste emoticons autosave ',
                toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
                         styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
                         table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen',
                menubar: false,
                height: 500,
                language: 'zh_CN',
                images_upload_handler: function (blobInfo, success, failure) {
                    var reader = new FileReader();
                    reader.readAsDataURL(blobInfo.blob());
                    reader.onload = function () {
                        success(this.result);
                    }
                }
            });

The plugins plug-in and toolbar toolbar contents are deleted and added by themselves, mainly images_upload_handler. Whether the TinyMCE5.x version is very powerful or the browser itself functions, the editor will automatically base 64 encoding and blob:http://protocol interoperability. What you see on the source code is non-base64 encoding

 

Advanced use of the Regex class Replace method in the background: This method has a delegation parameter that can be passed into a method where the main operation is performed (save base64 into space and return the reference string of the picture address)

Background asp.net(c#) code:

        public static string SaveBase64ToImageAndOutUrl(string htmlContent)
        {
            // Define regular expressions to match the base64 code in the src attribute of the img tag  
            string strImg = @"data\:image/(jpeg|png|gif|jpg|bmp);base64\,(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?";

            string content = Regex.Replace(htmlContent, strImg, new MatchEvaluator(CorrectString), RegexOptions.Compiled | RegexOptions.IgnoreCase);
            return content;
        }

        private static string CorrectString(Match match)
        {
            string imgSrc = match.Value;
            if (imgSrc.Substring(0, 10) != "data:image")
                return imgSrc;

            double size = imgSrc.Split(',')[1].TrimEnd('=').Length * .75;
if (size > Config.SiteConfig.ImageUploadSize * 1048576) throw new Exception("Some of the pictures in the content are too big!"); Response rsp = Upload.Base64ToImageAndSave(imgSrc, "/Upload"); if (rsp.Code == 0) throw new Exception(rsp.Message); return rsp.Data; }

  

The class Respones involved in the above code

    public class Response
    {
        /// <summary>
        /// Return code. 0 - Failure, 1 - Success
        /// </summary>
        public int Code { get; set; }

        /// <summary>
        /// Return message
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Return data
        /// </summary>
        public dynamic Data { get; set; }

        public Response()
        {
            Code = 0;
        }
    }

  

The above base64 method of saving pictures, please refer to the blog Park other heroes wrote, many, many, many, I will no longer post it.

 

The disadvantage is that the client will look at the source code very slowly. In addition, when many pictures or large pictures submit data, they should be set in web.config, otherwise they can not be submitted. 6MB is set here, and you can set the size as needed.

  <system.web>
    <! - The total length of form submission processing (maxRequest Length) is 6MB - >.
    <httpRuntime maxRequestLength="6291456"/>
  </system.web>

Posted by bivaughn on Sun, 08 Sep 2019 07:40:56 -0700