6

How can i add a custom/default button to the TinyMCE Editor, to be able to select a local image and insert it as RAW (BASE64) image at current position in editor?

STORM
  • 4,005
  • 11
  • 49
  • 98
  • What have you tried? Steps would seem to be: a) Add a button; b) Cause button to drive 'upload file' sequence; c) send file to server; d) retrieve base64 version from server and insert into active Editor. – pbuck Nov 20 '17 at 19:04
  • I habe no idea hownto implement it and why sending to server? Can TinyMCE or JS not convert it client side? – STORM Nov 20 '17 at 19:06
  • there's plenty existing documentation on tinymce buttons. As for sending to server, the issue is YOU can't read the file locally. You can send the file to a webserver, though. – pbuck Nov 20 '17 at 20:07
  • I have no chance to store the image on the server or send it to an webservice to convert it to raw. – STORM Nov 20 '17 at 20:23
  • Then look into javascript File API. It will let you read it in most clients. You'll get the file object (a Blob). Pass that into the File API `readAsArrayBuffer()`, and on load stuff back into tinymce. Yes, I'm doing some hand-waving, but that should get you started. I suggest you try first without tinymce to get the File stuff working & then integrate. – pbuck Nov 20 '17 at 22:17

1 Answers1

2

I just tried this from this answer.

window.onload = function () {
  document.getElementById("fileName").onchange = function () {
    var reader = new FileReader();
    reader.readAsDataURL(this.files[0]);
    reader.onload = function () {
      console.log(reader.result);
      document.getElementById("img").src = reader.result;
    };
    reader.onerror = function (error) {
      console.log('Error: ', error);
    };
  };
};
<input type="file" name="fileName" id="fileName" /><br />
<img src="https://dummyimage.com/250x75/000/fff.png&text=Select+an+Image" id="img" style="max-width: 250px; max-height: 75px;" />

Using the above URL (see console or inspect element and find the src) and with inserting an image at the current position, you can insert the image inside the document at the current position of caret.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252