CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Upload Images and Integrate with CKeditor in Asp.Net

By Bala Murugan
Posted On Apr 4,2012
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 15
Category: ASP.Net
Print this article.

Upload Images and Integrate with CKeditor in Asp.Net


CKeditor is one of the most widely used WYSIWYG editors for web applications. Overtime, the CKeditor continued to evolve by adding new features that made HTML text editing a lot easier. There are some useful articles already posted on codedigest for integrating CKeditor in your Asp.Net pages. Please see below,


Using CKEditor 3.x [a.k.a FCKeditor] with jQuery in ASP.Net

Using CKEditor 3.x[aka FCKeditor] in ASP.Net

Integrating FCKeditor in ASP.Net Websites – Part 1

Integrating FCKeditor in ASP.Net Websites – Part 2

 

 

When using a WYSIWYG editor, we will often need to upload image to server and embed it in the HTML content. By default, the CKeditor will support embedding an image that are already uploaded or from an external source by providing its URL (Click image icon in CKeditor toolbar we will get an “Image Properties” popup to insert an image).  See the image below,

Upload image and embed in CKeditor

 

By looking at the above popup it’s clear that the CKeditor does not provide an option by default to upload image and link it in the editor. To do this, there are some commercial options like ckuploader and CKFinder  available already that integrates very well with CKeditor. The ckuploader is a plug-in for CKeditor whereas the CKFinder is an Ajax file manager which can be used with or without CKeditor.

In this article, let’s see how we can upload image to our website and embed it in CKeditor without using the above paid solutions. This article will help us to do this in 2 ways,

  1. Using filebrowserImageUploadUrl property and providing our own implementation of a file uploader
  2. Using an external file uploader and embedding the image in CKeditor

 

Pre-requisites

To understand this article, create an ASP.Net Website in your Visual studio 2010 with the language of your choice. Download the latest version of CKeditor from its official site and unzip it to your local drive. At the time of this writing, the latest version of CKeditor is 3.6.2. You can refer the articles listed above for integrating the CKeditor in your Asp.Net site.

 

Using filebrowserImageUploadUrl property with our own implementation of a file uploader

The CKeditor has a property called filebrowserImageUploadUrl which will provide an option to upload images to the server when configured. This property takes a file uploader (a page or a handler) url to upload the selected image to the server. The handler that is responsible for uploading the image should return back the URL of the image to display in the CKeditor.

Once filebrowserImageUploadUrl property is configured, you will be able to see a new tab called “Upload” in Image Properties pop-up of CKeditor.  See the image below,

Upload image and embed in CKeditor

 

Now, the user can select an image and click “Send it to the server” button to upload and display in the editor.

The code for the page and the upload handler is below.

Default.aspx

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>

<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>

<script type="text/javascript">

    $(function () {

        CKEDITOR.replace('<%=txtCkEditor.ClientID %>', { filebrowserImageUploadUrl: '/CKeditorDemo/Upload.ashx' });

    });

</script>

</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">   

    <asp:TextBox ID="txtCkEditor" TextMode="MultiLine" runat="server"></asp:TextBox>

</asp:Content>

 

Upload.ashx

<%@ WebHandler Language="C#" Class="Upload" %>

 

using System;

using System.Web;

 

public class Upload : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

        HttpPostedFile uploads = context.Request.Files["upload"];

        string CKEditorFuncNum = context.Request["CKEditorFuncNum"];

        string file = System.IO.Path.GetFileName(uploads.FileName);

        uploads.SaveAs(context.Server.MapPath(".") + "\\Images\\" + file);

        string url = "/CKeditorDemo/Images/" + file;

        context.Response.Write("<script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\");</script>");

        context.Response.End();            

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

 

In the above code, we are uploading the selected image to a folder called “Images” found in root folder. The CKeditor will additionally pass a parameter called CKEditorFuncNum which will have the reference number of an anonymous function to callback after uploading. After uploading, the handler will return the script which will display the image in the main preview tab.

window.parent.CKEDITOR.tools.callFunction("CKEditorFuncNum", "url")

 

The above JavaScript CKeditor API is responsible for displaying the upload image in the preview tab of Image Properties tab.

 




Using an external file uploader and embedding the image in CKeditor

In this technique, we will provide image upload functionality externally to the CKeditor where the users can upload the images first. After uploading the images, the user can obtain the image URL and insert it to CKeditor through the insert image button in CKeditor toolbar.

An alternate and a more user friendly will be embedding the image in the cursor position of the CKeditor when the user clicks the uploaded image name in our page. Also, we can allow users to delete the uploaded images by providing a delete button. Something like below,

Upload image and embed in CKeditor

 

 

The user can delete the image by clicking delete link next to every image uploaded to the server.

 

Implementation

On click of Upload button, the images will be saved to “Images” folder and the name of the images will be displayed as hyperlinks with a delete link for each image. Using jQuery and the CKeditor JavaScript API the image will be inserted to the current cursor location of CKeditor on click of the image name link.

To implement delete, I will use a handler which will accept the image name and delete it from the Images folder. This handler will be called using Ajax method in jQuery. Refer the code below,

ASPX

<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>

<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>

<script type="text/javascript">

    $(function () {

        CKEDITOR.replace('<%=txtCkEditor.ClientID %>');

 

        $('#dvImages A.imglink').click(function () {

 

            var oEditor = CKEDITOR.instances.<%=txtCkEditor.ClientID %>;

            var html = "<img src='" + $(this).attr("imgsrc") + "' />";

 

            var newElement = CKEDITOR.dom.element.createFromHtml(html, oEditor.document);

            oEditor.insertElement(newElement);

        });

 

         $('#dvImages A.dellink').click(function () {

 

         var img =  $(this).attr("img");  

            $.ajax({

                  type: "POST",

                  url: "/CKeditorDemo/DeleteImage.ashx",

                  data: "imgname="+img,

                  contentType: 'application/x-www-form-urlencoded',               

                  success: function(response) {                 

                   if(response == "true")

                   {

                    $('#dvImages A.dellink[img=\"'+img+'\"]').fadeOut();

                    $('#dvImages A.imglink[imgsrc*=\"'+img+'\"]').fadeOut();                 

                   }     

                  },

                  error: function(response) {

                    alert('There was an error. ' + response);

                  }

                });

        });

 

    });

</script>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server"> 

<fieldset>

<h3>Upload mages</h3>

    <asp:FileUpload ID="FileUpload1" runat="server" /><br />

    <asp:FileUpload ID="FileUpload2" runat="server" /><br />

    <asp:FileUpload ID="FileUpload3" runat="server" /><br />

    <asp:FileUpload ID="FileUpload4" runat="server" /><br />

    <asp:Button ID="btnUpload" runat="server" Text="Upload"

        onclick="btnUpload_Click" />

<h3>Images</h3>

    <div id="dvImages">

    <asp:PlaceHolder ID="phImages" runat="server"></asp:PlaceHolder>

    </div>

</fieldset> 

    <asp:TextBox ID="txtCkEditor" TextMode="MultiLine" runat="server"></asp:TextBox>

</asp:Content>

 

Codebehind

protected void btnUpload_Click(object sender, EventArgs e)

    {

        string baseurlsave = Server.MapPath(".") + "\\Images\\";

        string baseurldisplay = "/CKeditorDemo/Images/";

        HttpFileCollection hfc = Request.Files;

        foreach (string file in hfc)

        {

           if (hfc[file].ContentLength > 0)

           {

            string filename = Path.GetFileName(hfc[file].FileName);

            hfc[file].SaveAs(baseurlsave + filename); 

           }

        }

      

        HyperLink hplImage = null;

        HyperLink hplDel = null;

        foreach (string file in Directory.GetFiles(baseurlsave))

        {

            string filename = Path.GetFileName(file);           

            hplImage = new HyperLink();

            hplDel = new HyperLink();

 

            //Image

            hplImage.NavigateUrl = "javascript:void()";

            hplImage.Attributes.Add("imgsrc", baseurldisplay + filename);

            hplImage.Text = filename;

            hplImage.CssClass = "imglink";

 

            //Delete link

            hplDel.NavigateUrl = "javascript:void()";

            hplDel.Attributes.Add("img", filename);

            hplDel.Text = "delete";

            hplDel.CssClass = "dellink";

 

            phImages.Controls.Add(hplImage);

            phImages.Controls.Add(new LiteralControl(" "));

            phImages.Controls.Add(hplDel);           

            phImages.Controls.Add(new LiteralControl("<br>"));

        }

       

    }

 

Delete handler

<%@ WebHandler Language="C#" Class="DeleteImage" %>

 

using System;

using System.Web;

 

public class DeleteImage : IHttpHandler {

 

    public void ProcessRequest(HttpContext context)

    {

        string filename = context.Request["imgname"];

        string baseurl = context.Server.MapPath(".") + "\\Images\\";

        try

        {

            System.IO.File.Delete(baseurl + filename);

        }

        catch

        {

            context.Response.Write("false");

            context.Response.End();

        }

        context.Response.Write("true");

        context.Response.End();

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

I have made my implementation as simple as possible to demonstrate easily. You can customize this so that the images are uploaded into a specific folder for each page.

Downloads

Download Source

Note: To run the sample, unzip the ckeditor source after downloading from the CKeditor official site and copy it to the application root. You need to copy the folder called ckeditor under the unzipped folder "ckeditor_3.6.2".


Conclusion

A full-fledged html editor should always support uploading and embedding images in the editor. Even though CKeditor provides a very good plug-in it may not be feasible solution for some of us since it is licensed. The 2 simple techniques discussed here will help you to implement an image uploader yourselves very easily for CKeditor. Download the source attached with this article and see it in action.

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
fastpokemap
Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing. Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.
http://appsforsys.com/fastpokemap/
Content copy error
Not Able to use the contents of this editor to assign to any string variable or any new page generated randomly on the go
Deleting Images from DB
Hello,

I'd like to thank you very much for this article, due to it I've finally handled the upload operation.
However, Im struggling with delete operation. Could u give me some tips as a code doesn't work.
w
rr
Error in ckeditor
$(function () {
CKEDITOR.replace('<%=txtCkEditor.ClientID %>', { filebrowserImageUploadUrl: '/CKeditorDemo/Upload.ashx' });
});
in these am getting an error JavaScript runtime error: 'CKEDITOR' is undefined how can i solve these please help me
its urgent
very good
Very useful information, saved my time and money ))
thank you very much
error please help
$(function () {
CKEDITOR.replace('<%=txtCkEditor.ClientID %>', { filebrowserImageUploadUrl: '/CKeditorDemo/Upload.ashx' });
});
in these am getting an error JavaScript runtime error: 'CKEDITOR' is undefined how can i solve these please help me
its urgent
Awesome Explanation
thanks for your code.it saved my day.
Parabéns
Ótimo post funcionou perfeitamente. Fácil e prático.
error this code
hi iam use this code but see this error when upload
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 11: // string strFileName = System.IO.Path.GetFileName(context.Request.Files[0].FileName);
Line 12: HttpPostedFile uploads = context.Request.Files["upload"];
Line 13: if (uploads.ContentLength <= 0)
Line 14: return;
Line 15:

Thank You
yes, this content is very useful to me thank you,,,,,,,,,
CKeditor in detailsview
Thanks for this sharing but I have a problem I want this image upload in a detailview edit item part. In edit item part I have ckeditor named CKEditorControl1. I have changed the code like below but it gives error:

CKEDITOR.replace('<%= (DetailsView1.FindControl("CKEditorControl1")).ClientID%>', { filebrowserImageUploadUrl: 'Upload.ashx' });


var oEditor = CKEDITOR.instances.<%= DetailsView1.FindControl("CKeditorControl1").ClientID%>;

How can I change this code to work??
uploading image
yes, this content is very useful to me thank you,,,,,,,,,
Thank you
i've been searching for so many solutions, and could get it to work.
Then i found you, finally i made it.
Thank you very much for your post.
^^"
Amazing!
Man you save me a lot of time! Thanks a lot for sharing this.