Ckeditor Upload image from clipboard

2 months ago

Get tired of download upload and then delete local file? How about just screen shot anywhere then pasted it to your text editor?

We will customize the pastedbase64 pluggin.

https://ckeditor.com/cke4/addon/pastebase64

Editor the pluggin.js file

(function () {
  "use strict";

  CKEDITOR.plugins.add("pastebase64", {
    init: init,
  });

  function init(editor) {
    if (editor.addFeature) {
      editor.addFeature({
        allowedContent: "img[alt,id,!src]{width,height};",
      });
    }

    editor.on("contentDom", function () {
      var editableElement = editor.editable
        ? editor.editable()
        : editor.document;
      editableElement.on("paste", onPaste, null, { editor: editor });
    });
  }

  function onPaste(event) {
    var editor = event.listenerData && event.listenerData.editor;
    var $event = event.data.$;
    var clipboardData = $event.clipboardData;
    var found = false;
    var imageType = /^image/;

    if (!clipboardData) {
      return;
    }

    return Array.prototype.forEach.call(
      clipboardData.types,
      function (type, i) {
        if (found) {
          return;
        }

        if (
          type.match(imageType) ||
          clipboardData.items[i].type.match(imageType)
        ) {
          console.log(clipboardData.items[i]);
          sendBlobImageToServer(clipboardData.items[i], editor);
          return (found = true);
        }
      }
    );
  }

  function sendBlobImageToServer(item, editor) {
    if (!item || typeof item.getAsFile !== "function") {
      return;
    }

    var file = item.getAsFile();
    var formData = new FormData();
    formData.append("upload", file);
    for (var pair of formData.entries()) {
      console.log(pair[0] + ", " + pair[1]);
    }
    // SEND FILE TO SERVER.
    fetch("/posts/image-clipboard", {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        var element = editor.document.createElement("img", {
          attributes: {
            src: data.url,
          },
        });
        setTimeout(function () {
          editor.insertElement(element);
        }, 10);
      })

      .catch((err) => {
        console.log(err);
      });
  }
})();

Nodejs server api

image_clipboard.js

const multiparty = require('multiparty'); //need this
const fs = require('fs'); //this come along with node.
const path = require('path');
const shortid = require('shortid');
const year = `${process.env.YEAR}`;

module.exports = function (req, res) {
  // parse a file upload
  const form = new multiparty.Form();
  console.log( req.body );
  console.log( req.files );
  // if(!req.fields) return res.status(400).send("not work");
  form.parse(req, function (err, fields, files) {
    console.log(files);
    if(!files) return res.status(400).send("not work");
    const img = files.upload; //array
    console.log(img);
    img.forEach(function (x) {
      fs.readFile(x.path, function (err, data) {
        console.log(err);
        if(err) return res.status(500).send('something went wrong!');
        const newName = shortid.generate(); // unique file name
        const ext = path.extname(x.originalFilename); // get file extension.
        // Need make up a file name + file ext.
        const path_file = `${process.env.STATIC_FILE_PATH}/${year}/${newName}${ext}`;
        const url = `/static/${year}/${newName}${ext}`;
        fs.writeFile(path_file, data, function (error) {
          if (error) return res.json(error);
          res.send({url});
        })
      })
    }); // end foreach
  });
}

If it not work then check your cache. Make sure your editor updated

Done