TinyMCE Image upload to seperate folder in .NET MVC

Gautam Gautam Donate Nov 13, 2019 · 15 mins read
TinyMCE Image upload to seperate folder in .NET MVC

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>       

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 () {
                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'


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".

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

                    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.ContentType = "application/json; charset=utf-8";
                            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!
Written by Gautam Sharma Profile
Developer, Writer, Emotional, loves to help, blogger

Connect with Gautam