Search code examples
javascriptbase64blobimage-uploadingtinymce-4

Using data URI instead of blob in TinyMCE 4 image upload


Using TinyMCE 4, I am trying to do a basic local file picker such as the one used in their example.

After running their example, I noticed that the generated image source is a blob opposed to a base64.

So my question: is it possible to use base64 instead of a blob?

I thought the first argument of the file_picker_callback callback would be used as the source of the image, so I tweaked the code using this answer where I pass the data URI as the first argument.

file_picker_types: 'image', 
// and here's our custom image picker
file_picker_callback: function (cb, value, meta) {
    var input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');

    // Note: In modern browsers input[type="file"] is functional without 
    // even adding it to the DOM, but that might not be the case in some older
    // or quirky browsers like IE, so you might want to add it to the DOM
    // just in case, and visually hide it. And do not forget do remove it
    // once you do not need it anymore.

    input.onchange = function() {
        var file = this.files[0];
        var reader = new FileReader();

        reader.onload = function () {

            // Note: Now we need to register the blob in TinyMCEs image blob
            // registry. In the next release this part hopefully won't be
            // necessary, as we are looking to handle it internally.
            //var id = 'blobid' + (new Date()).getTime();
            //var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
            //var base64 = reader.result.split(',')[1];
            //var blobInfo = blobCache.create(id, file, base64);

            //blobCache.add( blobInfo );

            // call the callback and populate the Title field with the file name

            cb(reader.result, { title: 'hola' });
        };
        reader.readAsDataURL( file );
    };

    input.click();
}

However it did not work and instead converted the source into a blob e.g.

<img src="blob:null/c8e90adb-4074-45b8-89f4-3f28c66591bb" alt="" /> 

If I pass a normal string e.g. test.jpg, it will generate

<img src="test.jpg" alt="" />

Solution

  • The blob: format you see is actually a Base64 encoded binary image. If you were to post the content of TinyMCE to the server you would indeed get the Base64 data.

    You can force TinyMCE to immediately send that image to your server to get converted to a "regular" image by following these steps:

    https://www.tinymce.com/docs/advanced/handle-async-image-uploads/