Posted in Web Development

Enable image uploading in summernote text editor

How to upload image to the server using Summernote text editor plugin

Summernote is a great plugin for using as a WYSIWYG rich text editor in the browser. You can easily integrate it with HTML textarea in your website or web application. While developing an application which stores and displays rich text, it’s almost always required to have image uploading feature inside the text editor. Summernote does have this feature but with a catch. Summernote converts the uploaded images to base64 encoding. This brings about several problems:

  • Inefficient way to store image in database.
  • HTML pages with base64 encoded images take significantly longer to load in the browser.
  • No public URL will be available for the image.
  • Post processing of image is almost impossible.
  • Takes more space to store the images in the database.
  • Database backups take longer time.

Good news is, we can easily alter this and make uploading images in summernote lot more efficient. Let’s see the best way to upload images using summernote:

Add a textarea in your HTML form

<textarea class="textarea" placeholder="Place some text here"  name="body" style="width: 100%; height: 400px;">
</textarea>

Initialize Summernote with textarea
We are using jQuery to select the textarea. the onImageUpload is a callback function which gets triggered every time user uploads an image in summernote. The files parameter provides the uploaded files as an array.

$(document).ready(function() {
    $('.textarea').summernote({
        callbacks: {
            onImageUpload: function(files)  {
                // taking the first image/file from the array
                uploadFile(files[0]);
            }
        }
    });
});

uploadFile() is a custom function which handles file uploading via AJAX (or you can use any other API to make the request).

First of all, we have to make a FormData Object and append the file from the files array into the FormData object. The url is the file upload endpoint from the backend system. We can use insertImage feature of Summernote to add the uploaded image in our textarea.
Have a look at the code below:

function uploadFile(file)  {
    var data = new FormData();
    data.append("file",file);
    $.ajax({
        method: 'POST',
        data: data,
        url: '/upload-image', // replace with your endpoint
        cache: false,
        contentType: false,
        processData: false,
        success: function(res)  {
            // Displaying the uploaded image in the textarea 
            $(".textarea").summernote("insertImage", res['url']);
        }
    });
}

And Done!

NB. This tutorial is based on Summer note v0.8.18. For older summernote versions, this approach won’t work.