Upload EditorJS Image Object to WordPress REST API

Question

I’m using EditorJS as frontend content editor in my project. Now I can add new posts and edit my posts. I’m doing these with the WordPress REST API. But I don’t know how to upload media items with post to REST API. I’m using EditorJS’s Image Block. Click for block’s doc.

This is my editorFunctions.js file

function convertParagraph(elType, elData){
    elDataText = elData.text;
    return '<p>' + elDataText + '</p>';
  }
  
  function convertHeader(elType, elData) {
    elDataText = elData.text;
    elDataLevel = elData.level;
    return '<h' + elDataLevel + '>' + elDataText + '</h' + elDataLevel + '>'; 
  }
  
  function convertChecklist(elType, elData) {
    elItems = elData.items;
    dummy_string = '';
    for (i=0; i < elItems.length; i++) { 
        elItem = elItems[i];
        elItemText = elItem.text;
        isChecked = elItem.checked ? 'checked' : '';
        dummy_string = dummy_string.concat('<label><input type="checkbox" ' + isChecked + '>' + elItemText + '</label>');
    }
    return dummy_string;
  }
  
  function convertEmbed(elType, elData) {
    let elId = el['id'];
    let elSource = elData['embed'];
    let elHeight = elData['height'];
    let elWidth = elData['width'];
    let elCaption = elData['caption'];
    return '<iframe id="' + elId + '" style="width: 100%;" src="' + elSource + '" height="' + elHeight + '"></iframe><style> #'+ elId +'::after {content: "'+ elCaption +'"} </style>';
  }
  
  function convertList(elType, elData) {
    let listStyle = elData['style'];
    let elItems = elData['items'];
    let dummy_string = '';
    if (listStyle == 'ordered') { var correntStyle="ol";} else { var correntStyle="ul"; };
    for (i=0; i < elItems.length; i++) { 
        elText = elItems[i];
        dummy_string = dummy_string.concat('<li>'+ elText +'</li>');
    }
    return '<' + correntStyle +'>' + dummy_string + '</'+ correntStyle +'>';
  }
  
  function type_to_el(el) {
  
    let elType = el['type'];
    let elData = el['data'];
  
    if (elType == 'paragraph') {
      return convertParagraph(elType, elData);
    }
    if (elType == 'header') {
      return convertHeader(elType, elData);
    }
    if (elType == 'checklist') {
      return convertChecklist(elType, elData);
    }
    if (elType == 'embed') {
      return convertEmbed(elType, elData);
    }
    if (elType == 'list') {
      return convertList(elType, elData);
    }
  }
  
  function sendPostToDB(outputData, status="draft", post_id = '') {
    let postTitle = $("#postTitle").val();
    let postExcerpt = $("#postExcerpt").val();
    let postTags = $("#postTags").val();
  
    var blockArray = outputData.blocks;
    
    let allContent="";
  
    for (let i=0; i < blockArray.length; i++) {
      let el = blockArray[i];
      allContent = allContent.concat(type_to_el(el));
    }
  
    outputData = JSON.stringify(outputData)

    if (post_id == '') {
      let mainData = {
        "title"   : postTitle,
        "content" : allContent,
        "excerpt" : postExcerpt,
        // "tags"    : postTags,
        "status"  : status, 
        "meta"    : {
          "rawData" : outputData,
        }
      }
      let postSender = new XMLHttpRequest();
    
      postSender.open("POST", homeUrl + '/wp-json/wp/v2/posts');
    
      postSender.setRequestHeader("X-WP-NONCE", nonceData.nonce);
      postSender.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      postSender.send(JSON.stringify(mainData));
      postSender.onreadystatechange = function() {
        if (postSender.readyState == 4) {
          if (postSender.status == 201) {
            // window.location.replace(homeUrl + '/yazilarim');
          }
          else {
            console.log('HATA');
          }
        }
      }
    } else {
      let mainData = {
        "id"      : post_id,
        "title"   : postTitle,
        "content" : allContent,
        "excerpt" : postExcerpt,
        // "tags"    : postTags,
        "status"  : status, 
        "meta"    : {
          "rawData" : outputData,
        }
      }
      let postSender = new XMLHttpRequest();
    
      postSender.open("POST", homeUrl + '/wp-json/wp/v2/posts/' + post_id);
    
      postSender.setRequestHeader("X-WP-NONCE", nonceData.nonce);
      postSender.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      postSender.send(JSON.stringify(mainData));
      postSender.onreadystatechange = function() {
        if (postSender.readyState == 4) {
          if (postSender.status == 201) {
            // window.location.replace(homeUrl + '/yazilarim');
          }
        }
      }
    }
  }

This is my editorJS config file

const tools = {
  header: {
    class: Header,
    inlineToolbar: ["link"],
  },
  list: {
    class: List,
    inlineToolbar: true,
  },
  checklist: {
    class: Checklist,
    inlineToolbar: true,
  },
  embed: {
    class: Embed,
    inlineToolbar: true,
  },
  markertool: {
    class: MarkerTool,
    inlineToolbar: true,
  },
  image: {
    class: ImageTool,
    config: {
      additionalRequestHeaders: {
        "X-WP-NONCE" : nonceData.nonce,
      },
      uploader: {
        uploadByFile(file){
          let mainData = {
            "id"    : 'pkImg-' + file.lastModified,
            "date"  : file.lastModified,
            "body"  : file,
          }
          console.log(mainData);
          let imageUploader = new XMLHttpRequest();
          imageUploader.open("POST", homeUrl + '/wp-json/wp/v2/media/');
          imageUploader.setRequestHeader("X-WP-NONCE", nonceData.nonce);
          imageUploader.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
          return imageUploader.upload.then(() => {
            return {
              success: 1,
              file: {
                // url: 'https://exmaple.com/images/image.jpg',
                // any other image data you want to store, such as width, height, color, extension, etc
              }
            };
          });
        }
      }
    }
  },
};

const editor = new EditorJS({
  /**
   * Id of Element that should contain the Editor
   */

  holder: "editorjs",

  /**
   * Available Tools list.
   * Pass Tool's class or Settings object for each Tool you want to use
   */

  tools,
});

editor.isReady
  .then(() => {
    let editorTop = $("#editorTop");
    let editorBottom = $("#editorBottom");
    let titleInputAttrs = {
      id: "postTitle",
      name: "postTitle",
      placeholder: "Başlık",
      type: "text",
    };
    let excerptInputAttrs = {
      id: "postExcerpt",
      name: "postExcerpt",
      placeholder: "Özet",
      type: "textarea",
    };
    let tagInputAttrs = {
      id: "postTags",
      name: "postTags",
      placeholder: "Etiketler",
      type: "text",
    };
    $("<input>").attr(titleInputAttrs).appendTo(editorTop);
    $("<textarea>").attr(excerptInputAttrs).appendTo(editorBottom);
    $("<input>").attr(tagInputAttrs).appendTo(editorBottom);
    console.log("Editor.js is ready to work!");
    /** Do anything you need after editor initialization */
  })
  .catch((reason) => {
    console.log(`Editor.js initialization failed because of ${reason}`);
  });

$("#pkSendPost").on("click", function () {
  editor
    .save()
    .then((outputData) => {
      sendPostToDB(outputData, 'pending');
    })
    .catch((error) => {
      console.log("Saving failed: ", error);
    });
});

$("#pkSavePost").on("click", function () {
  editor
    .save()
    .then((outputData) => {
      sendPostToDB(outputData, 'draft');
    })
    .catch((error) => {
      console.log("Saving failed: ", error);
    });
});

EditorJS image block is returning this:

File { 
   name: "Gauge.png",
   lastModified: 1641031649209,
   webkitRelativePath: "",
   size: 7534,
   type: "image/png"
}

0
Emirhan Gümüş 4 days 2022-01-15T03:16:34-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse