Programming

TinyMCE Image upload to seperate folder in .NET MVC

Gautam Gautam Aug 08, 2019 · 15 mins read
TinyMCE Image upload to seperate folder in .NET MVC

 

 

Share

TinyMCE is a great open-source Rich Text editor available online, if you want to use a paid version, I recommend using Froala Editor. It has got many cool features that every developer would love to use, however its up to you to choose the best one!

In this article, I share how to upload images to a seperate folder from TinyMCE in ASP.NET MVC, since TinyMCE links images as blob, and sometimes it becomes hard to identify your images and other references. 

Step 1: Create an Empty Project

Open Visual Studio, you can download it from here. I'm using Visual Studio 2017, Create an Empty Project, go to File → New → Project as described in Screenshot below.

Next, select Web from the templates listed on Left Panel, next select ASP.NET Web Application (.NET Framework), provide your desired name for your Project, I've used - "ImageUploadTinyMCE", next Press OK, let the project build finish.

You will see the default contents included in the Project, remove or add them as per your needs. 

Step 2: Add reference to TinyMCE

Download your TinyMCE build from TinyMCE official site here, extract the downloaded package and copy it to your Project's Content folder and your CSS directory.

Step 3: Coding and Testing

Now, its time to build, I'm using Home Page to place my editor, open the file, navigate to Solution Explorer → Views → Home → Index.cshtml. Delete the default HTML code already written there and replace it with your contents. 

Add one textarea for the TinyMCE, and scripts section to write the JS code. 

Placing the textarea code:

<div class="row">
    <div class="col-md-8">
        <label>Image Upload</label>
        <textarea class="form-control" placeholder="contents" id="txtContent" rows="4"></textarea>       
    </div>
</div>

Please note the ID of the textbox, since we will be refrencing it with TinyMCE using its ID, Now, add the scripts contents, ASP.NET MVC default layout already has the section defined for scripts contents, you can check it on the _Layout file, placed in the Shared folder. Navigate to Solution Explorer → Views → Shared → _Layout.cshtml, scroll down to bottom and look for the scripts section defined as below:

@RenderSection("scripts", required: false)

This section will render all the scripts that you define in any page having the master file as _Layout.cshtml.

Now write the script for TinyMCE configuration in Index.cshtml file by defining section for scripts as:

@section scripts{
    <script src="~/Content/tinymce/tinymce.min.js"></script>
    <script src="~/Content/tinymce/plugins/image/plugin.min.js"></script>

    <script type="text/javascript">
        $(function () {
            tinymce.init({
                selector: '#txtContent',
                plugins: [
                    "autoresize 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 placeholder codesample"
                ],
                menubar: false,
                image_advtab: false,
                toolbar: "undo redo | bold italic underline| blockquote codesample | alignleft aligncenter alignright alignjustify | bullist numlist | link image media | emoticons",
                max_height: 700,
                min_height: 450,
                statusbar: false,
                placeholder: "Start writing your contents here ...",
                paste_data_images: true,
                advimagescale_filter_class: "img-fluid",
                images_upload_url: '/Home/UploadFiles',
                image_dimensions: false,
                image_class_list: [
                    { title: 'None', value: 'img img-responsive' }
                ],
                style_formats: [
                    {
                        title: 'Image Left', selector: 'img', styles: {
                            'float': 'left',
                            'margin': '0 10px 0 10px',
                            'max-width': '600px',
                            'width': '500px'
                        }
                    }

                ]
            });
        });
    </script>
}

First you must provide reference to TinyMCE js file and image plugin Js file:

<script src="~/Content/tinymce/tinymce.min.js"></script>
<script src="~/Content/tinymce/plugins/image/plugin.min.js"></script>

 Next add the control images_upload_url as to your upload method defined in Controller file. 

images_upload_url: '/Home/UploadFiles'

Now press Ctrl+M+G, or simply right click on file and choose first option to open Controller of that file or you can simply navigate to Solution Explorer → Controllers → HomeController.cs, add the following method:

Note, the name provided in image_upload_url must be same as of in this method i.e. UploadFiles, make this file as HTTPPOST method, we will be accepting image as Request.Files with name of "file".

 [HttpPost]
public string UploadFiles()
{
            if (Request.Files["file"] != null)
            {
                var file = Request.Files["file"];
                string TargetLocation = Server.MapPath("~/Uploads/");

                try
                {
                    if (file.ContentLength > 0)
                    {
                        // Get File Extension
                        string Extension = Path.GetExtension(file.FileName).ToLower();

                        // Determining file name. You can format it as you wish.
                        string FileName = Path.GetFileName(file.FileName);
                        FileName = Guid.NewGuid().ToString().Substring(0, 8);

                        // Determining file size.
                        int FileSize = file.ContentLength;

                        // Creating a byte array corresponding to file size.
                        byte[] FileByteArray = new byte[FileSize];

                        // Basic validation for file extension
                        string[] AllowedExtension = { ".gif", ".jpeg", ".jpg", ".png", ".svg", ".blob" };
                        string[] AllowedMimeType = { "image/gif", "image/jpeg", "image/pjpeg", "image/x-png", "image/png", "image/svg+xml" };

                        if (AllowedExtension.Contains(Extension) && AllowedMimeType.Contains(MimeMapping.GetMimeMapping(file.FileName)))
                        {
                            // Posted file is being pushed into byte array.
                            file.InputStream.Read(FileByteArray, 0, FileSize);

                            // Uploading properly formatted file to server.
                            file.SaveAs(TargetLocation + FileName + Extension);
                            string json = "";
                            Hashtable resp = new Hashtable();
                            string urlPath = MapURL(TargetLocation) + FileName + Extension;

                            // Make the response an json object
                            resp.Add("location", urlPath);
                            json = JsonConvert.SerializeObject(resp);

                            // Clear and send the response back to the browser.
                            Response.Clear();
                            Response.ContentType = "application/json; charset=utf-8";
                            Response.Write(json);
                            Response.End();
                        }
                        else
                        {
                            return "File type not supported. Try another.";
                        }
                    }
                }

                catch (Exception ex)
                {
                    // Handle errors
                    return "Could not upload. Please try again";
                }
            }
            return "No Image";
}

To Map the URL of the uploaded Image write the following method.

private string MapURL(string path)
{
      string appPath = Server.MapPath("/").ToLower();
      return string.Format("/{0}", path.ToLower().Replace(appPath, "").Replace(@"\", "/"));
}

Now save it and run/debug your project, in the browser, drag and drop any Image to the editor and see it in action.

Immediately after uploading dropping the image, you will see the UploadFiles method is being called, 

You'll see the Request.Files containing Key having file, save its value to a variable for future use. 

var file = Request.Files["file"];

Now its time to check the saved image in your folder:

Check in your browser for image link - 

Check it in your TinyMCE image editor - 

That's it, you can modify it according to your needs and style. Thanks for reading!

Join Newsletter
Get the latest news right in your inbox. We never spam!
Gautam
Written by Gautam Sharma Profile
Hi Gautam here, I'm a Web Developer, a blogger, loves to travel and explore! helping old and poors and needys'! Follow me on social networks - Facebook, Twitter.

Automate WhatsApp with PyAutoGUI

Automatically send WhatsApp messages at a given time using PyAutoGUI, a module to automate GUI of a computer by emulating keyboad and mouse movements...

Mithu Mondal In Programming about 6 days ago

Basic OSPF Configuration - CCNA

OSPF was designed expressly for IP networks and it supports IP subnetting and tagging of externally derived routing information.

Gautam Sharma In Programming about 1 months ago