bitshift
bitshift

Reputation: 6842

Using CKEditor custom filebrowser and upload with ASP.Net MVC

I have a MVC app that Im trying to use CKEditor with. One example I was looking at is here but there are many others. So far so good, but one section im still curious about, is the js that sends the selected file name back to the file upload dialog textbox.

<script type="text/javascript">
    $(document).ready(function () {
        $(".returnImage").click("click", function (e) {
            var urlImage = $(this).attr("data-url");
            window.opener.updateValue("cke_72_textInput", urlImage);
            window.close();
        });
    });
</script>

In particular, the cke_72_textInput element. My example wasnt working initially, until I opened chrome dev tools and found the actual id of the textinput, which was in my case cke_76_textInput. Why the id change I wonder? Seems a little "fragile" to refer to a specific id like this? The above js code just takes the selected image file and returns it into the textbox of the fileupload dialog.

Is there something exposed that references this textbox element indirectly without specifying it by id (via the config for example)?

Upvotes: 1

Views: 1585

Answers (2)

hammad
hammad

Reputation: 21

On view:

$(document).ready(function () {   

 CKEDITOR.replace('Text-area-name', {
            filebrowserImageUploadUrl: '/Controller-name/UploadImage'
        });

        CKEDITOR.editorConfig = function (config) {
            // Define changes to default configuration here. For example: 
            config.language = 'de';
            // config.extraPlugins = 'my_own_plugin'; // if you have any plugin 
            // config.uiColor = '#AADC6E'; 
            // config.image_previewText = CKEDITOR.tools.repeat(' Hier steht dann dein guter Text. ', 8 ); 
            // config.contentsLanguage = 'de'; 
            config.height = 350; // 350px, specify if you want a larger height of the editor 

            config.linkShowAdvancedTab = false;
            config.linkShowTargetTab = false;
        };

 CKEDITOR.on('dialogDefinition', function (ev) {
            var dialogName = ev.data.name;
            var dialogDefinition = ev.data.definition;
            ev.data.definition.resizable = CKEDITOR.DIALOG_RESIZE_NONE;

            if (dialogName == 'link') {
                var infoTab = dialogDefinition.getContents('info');
                infoTab.remove('protocol');
                dialogDefinition.removeContents('target');
                dialogDefinition.removeContents('advanced');
            }

            if (dialogName == 'image') {
                dialogDefinition.removeContents('Link');
                dialogDefinition.removeContents('advanced');
                var infoTab = dialogDefinition.getContents('info');
                infoTab.remove('txtBorder');
                infoTab.remove('txtHSpace');
                infoTab.remove('txtVSpace');
                infoTab.remove('cmbAlign');
            }
        });

    }

On Contoller:

 [HttpPost]
    public ActionResult UploadImage(HttpPostedFileBase file, string CKEditorFuncNum, string CKEditor, string langCode)
    {
     if (file.ContentLength <= 0)
            return null;

        // here logic to upload image
        // and get file path of the image

        const string uploadFolder = "Assets/img/";

        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath(string.Format("~/{0}", uploadFolder)), fileName);
        file.SaveAs(path);

        var url = string.Format("{0}{1}/{2}/{3}", Request.Url.GetLeftPart(UriPartial.Authority),
            Request.ApplicationPath == "/" ? string.Empty : Request.ApplicationPath,
            uploadFolder, fileName);

        // passing message success/failure
        const string message = "Image was saved correctly";

        // since it is an ajax request it requires this string
        var output = string.Format(
            "<html><body><script>window.parent.CKEDITOR.tools.callFunction({0}, \"{1}\", \"{2}\");</script></body></html>",
            CKEditorFuncNum, url, message);

        return Content(output);
    }

Upvotes: 2

Seth
Seth

Reputation: 426

I had the same problem...a little frustrating that I couldn't find any official documentation, considering this seems like a common use case.

Anyways, take a look at the quick tutorial here: http://r2d2.cc/2010/11/03/file-and-image-upload-with-asp-net-mvc2-with-ckeditor-wysiwyg-rich-text-editor/. In case the link ever breaks, here's what I did.

    [HttpPost]
    public ActionResult UploadImage(HttpPostedFileBase upload, string ckEditorFuncNum)
    {
        /* 
           add logic to upload and save image here
        */

        var path = "~/Path/To/image.jpg"; // Logical relative path to uploaded image
        var url = string.Format("{0}://{1}{2}", 
            Request.Url.Scheme, 
            Request.Url.Authority, 
            Url.Content(path)); // URL path to uploaded image
        var message = "Saved!"; // Optional

        var output = string.Format("<script>window.parent.CKEDITOR.tools.callFunction({0}, '{1}', '{2}');</script>", 
            CKEditorFuncNum, 
            url, 
            message);
        return Content(output);
    }

Upvotes: 1

Related Questions