简体   繁体   中英

Upload image at client side and convert it to base64 for generating html

I am composing an email body with the help of CKEDITOR. I want to add an image in message body in it of base64 format. So that I can send encoded image along the body without the need of storing image on a server.

I know can be achieved in in TinyMCE without sending on server. How can we achieve this in CKEDITOR?

So far I have tried with

CKEDITOR.replace('editor1', {
   //filebrowserBrowseUrl:'xx',
   filebrowserUploadUrl: 'base64'
});
CKEDITOR.config.extraPlugins = "base64image";

I also have a method ready to convert url to base64 like

function getBase64FromImageUrl(url) {
     var img = new Image();

     img.setAttribute('crossOrigin', 'anonymous');

 img.onload = function () {
       var canvas = document.createElement("canvas");
       canvas.width = this.width;
       canvas.height = this.height;

       var ctx = canvas.getContext("2d");
       ctx.drawImage(this, 0, 0);

       var dataURL  = canvas.toDataURL("image/png");

       alert(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
    };

  img.src = url;
}

You do not have to use canvas for that. Have a look at insertHtml . I use this function within a custom plugin:

function getBase64(fileData, editor)
{
    var reader = new FileReader();
    reader.addEventListener("load", function (e) {
        var result = e.target.result;

        if (editor)
        {
            editor.insertHtml('<img src="' + result + '">');
        }
    });

    reader.readAsDataURL(fileData);
}

Edit: OP: "How CKEditor can pass values to this functions?" In my case it is a simple plugin which constist of the getBase64-function, a modal (alike) dialog for getting/selecting the image path and its logic. Within this small dialog is a input:

<input type="file" id="fileLoader" name="files" title="Load File" />

In the dialogs logic I get the file with this code:

var imagePath = null;
var fileLoader = $(this).find('#fileLoader');
if (fileLoader)
{
    var fileData = null;
    imagePath = fileLoader.val();

    if (fileLoader.files && fileLoader.files[0]) {

        fileData = fileLoader.files[0];
        }
        if (fileData == null) {
            if (fileLoader.length && fileLoader.length > 0) {
                fileLoader = fileLoader[0];
                if (fileLoader.files && fileLoader.files[0]) {

                    fileData = fileLoader.files[0];
                    }
                }
            }

This file data you can pass to the getBase64 function. You may also have a look on this simple plugin tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM