How to Add a Local File Picker to Image Dialog in TinyMCE

TinyMCE is web-based WYSIWYG editor that converts HTML elements to an editor. It provides an instant ability to add HTML editor to textarea in the web page. You can easily add TinyMCE editor to HTML element by writing minimal JavaScript Code.
In the example code, we will integrate image uploading functionality in TinyMCE editor. This will add local file picker to the Image dialog and allow the user to upload image in TinyMCE editor.

HTML Code
Specify an HTML element (textarea) to add a WYSIWYG HTML Editor.

1
<textarea name="editor" id="editor"></textarea>

TinyMCE jQuery Plugin
At first download the TinyMCE jQuery plugin from here and include the TinyMCE JS library in the web page.

1
<script type="text/javascript" src="tinymce/tinymce.min.js"></script>

Note that: All the necessary TinyMCE libraries are included in our source code. So, you don’t need to download the TinyMCE jQuery plugin separately.

JavaScript Code:
The following JavaScript code will replace textarea with TinyMCE editor instance by passing the selector #editor.

An image tool will be provided to insert and edit the image.
An image dialog will appear to select an image.
A local file picker will be added to the Image dialog for upload image from computer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<script>
tinymce.init({
  selector: '#editor',
  plugins: 'image code',
  toolbar: 'undo redo | link image | code',
  // enable title field in the Image dialog
  image_title: true,
  // enable automatic uploads of images represented by blob or data URIs
  automatic_uploads: true,
  // add custom filepicker only to Image dialog
  file_picker_types: 'image',
  file_picker_callback: function(cb, value, meta) {
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', 'image/*');

    input.onchange = function() {
      var file = this.files[0];
      var reader = new FileReader();
     
      reader.onload = function () {
        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(blobInfo.blobUri(), { title: file.name });
      };
      reader.readAsDataURL(file);
    };
   
    input.click();
  }
});
</script>

tinymce-file-picker-upload-image-from-computer
Saving TinyMCE Editor Content
To save the TinyMCE editor content, an HTML form needs to be submitted. Once the

READ  How to Move Marker Smoothly on Google Map using JavaScript
is submitted, you can get the editor HTML content using $_POST variable in PHP.

1
$_POST['editor'];