2.9.0 • Published 6 months ago

@editorjs/image v2.9.0

Weekly downloads
5,909
License
MIT
Repository
github
Last release
6 months ago

npm.io

Image Tool

Image Block for the Editor.js.

npm.io

Features

  • Uploading file from the device
  • Pasting copied content from the web
  • Pasting images by drag-n-drop
  • Pasting files and screenshots from Clipboard
  • Allows adding a border, and a background
  • Allows stretching an image to the container's full-width

Notes

This Tool requires server-side implementation for the file uploading. See backend response format for more details.

This Tool is also capable of uploading & displaying video files using the <video> element. To enable this, specify video mime-types via the 'types' config param.

Installation

Get the package

yarn add @editorjs/image

Include module at your application

import ImageTool from '@editorjs/image';

Optionally, you can load this tool from JsDelivr CDN

Usage

Add a new Tool to the tools property of the Editor.js initial config.

import ImageTool from '@editorjs/image';

// or if you inject ImageTool via standalone script
const ImageTool = window.ImageTool;

var editor = EditorJS({
  ...

  tools: {
    ...
    image: {
      class: ImageTool,
      config: {
        endpoints: {
          byFile: 'http://localhost:8008/uploadFile', // Your backend file uploader endpoint
          byUrl: 'http://localhost:8008/fetchUrl', // Your endpoint that provides uploading by Url
        }
      }
    }
  }

  ...
});

Config Params

Image Tool supports these configuration parameters:

FieldTypeDescription
endpoints{byFile: string, byUrl: string}Endpoints for file uploading. Contains 2 fields: byFile - for file uploading byUrl - for uploading by URL
fieldstring(default: image) Name of uploaded image field in POST request
typesstring(default: image/*) Mime-types of files that can be accepted with file selection.
additionalRequestDataobjectObject with any data you want to send with uploading requests
additionalRequestHeadersobjectObject with any custom headers which will be added to request. See example
captionPlaceholderstring(default: Caption) Placeholder for Caption input
buttonContentstringAllows to override HTML content of «Select file» button
uploader{{uploadByFile: function, uploadByUrl: function}}Optional custom uploading methods. See details below.
actionsarrayArray with custom actions to show in the tool's settings menu. See details below.

Note that if you don't implement your custom uploader methods, the endpoints param is required.

Tool's settings

npm.io

  1. Add border

  2. Stretch to full-width

  3. Add background

Add extra setting-buttons by adding them to the actions-array in the configuration:

actions: [
    {
        name: 'new_button',
        icon: '<svg>...</svg>',
        title: 'New Button',
        toggle: true,
        action: (name) => {
            alert(`${name} button clicked`);
        }
    }
]

NOTE: return value of action callback for settings whether action button should be toggled or not is deprecated. Consider using toggle option instead.

Output data

This Tool returns data with following format

FieldTypeDescription
fileobjectUploaded file data. Any data got from backend uploader. Always contain the url property
captionstringimage's caption
withBorderbooleanadd border to image
withBackgroundbooleanneed to add background
stretchedbooleanstretch image to screen's width
{
    "type" : "image",
    "data" : {
        "file": {
            "url" : "https://www.tesla.com/tesla_theme/assets/img/_vehicle_redesign/roadster_and_semi/roadster/hero.jpg"
        },
        "caption" : "Roadster // tesla.com",
        "withBorder" : false,
        "withBackground" : false,
        "stretched" : true
    }
}

Backend response format

This Tool works by one of the following schemes:

  1. Uploading files from the device
  2. Uploading by URL (handle image-like URL's pasting)
  3. Uploading by drag-n-drop file
  4. Uploading by pasting from Clipboard

Uploading files from device

Scenario:

  1. User select file from the device
  2. Tool sends it to your backend (on config.endpoints.byFile route)
  3. Your backend should save file and return file data with JSON at specified format.
  4. Image tool shows saved image and stores server answer

So, you can implement backend for file saving by your own way. It is a specific and trivial task depending on your environment and stack.

The tool executes the request as multipart/form-data, with the key as the value of field in configuration.

The response of your uploader should cover the following format:

{
    "success" : 1,
    "file": {
        "url" : "https://www.tesla.com/tesla_theme/assets/img/_vehicle_redesign/roadster_and_semi/roadster/hero.jpg",
        // ... and any additional fields you want to store, such as width, height, color, extension, etc
    }
}

success - uploading status. 1 for successful, 0 for failed

file - uploaded file data. Must contain an url field with full public path to the uploaded image. Also, can contain any additional fields you want to store. For example, width, height, id etc. All additional fields will be saved at the file object of output data.

Uploading by pasted URL

Scenario:

  1. User pastes an URL of the image file to the Editor
  2. Editor pass pasted string to the Image Tool
  3. Tool sends it to your backend (on config.endpoints.byUrl route) via 'url' in request body
  4. Your backend should accept URL, download and save the original file by passed URL and return file data with JSON at specified format.
  5. Image tool shows saved image and stores server answer

The tool executes the request as application/json with the following request body:

{
  "url": "<pasted URL from the user>"
  "additionalRequestData": "<additional request data from configuration>"
}

Response of your uploader should be at the same format as described at «Uploading files from device» section

Uploading by drag-n-drop or from Clipboard

Your backend will accept file as FormData object in field name, specified by config.field (by default, «image»). You should save it and return the same response format as described above.

Providing custom uploading methods

As mentioned at the Config Params section, you have an ability to provide own custom uploading methods. It is a quite simple: implement uploadByFile and uploadByUrl methods and pass them via uploader config param. Both methods must return a Promise that resolves with response in a format that described at the backend response format section.

MethodArgumentsReturn valueDescription
uploadByFileFile{Promise.<{success, file: {url}}>}Upload file to the server and return an uploaded image data
uploadByUrlstring{Promise.<{success, file: {url}}>}Send URL-string to the server, that should load image by this URL and return an uploaded image data

Example:

import ImageTool from '@editorjs/image';

var editor = EditorJS({
  ...

  tools: {
    ...
    image: {
      class: ImageTool,
      config: {
        /**
         * Custom uploader
         */
        uploader: {
          /**
           * Upload file to the server and return an uploaded image data
           * @param {File} file - file selected from the device or pasted by drag-n-drop
           * @return {Promise.<{success, file: {url}}>}
           */
          uploadByFile(file){
            // your own uploading logic here
            return MyAjax.upload(file).then(() => {
              return {
                success: 1,
                file: {
                  url: 'https://codex.so/upload/redactor_images/o_80beea670e49f04931ce9e3b2122ac70.jpg',
                  // any other image data you want to store, such as width, height, color, extension, etc
                }
              };
            });
          },

          /**
           * Send URL-string to the server. Backend should load image by this URL and return an uploaded image data
           * @param {string} url - pasted image URL
           * @return {Promise.<{success, file: {url}}>}
           */
          uploadByUrl(url){
            // your ajax request for uploading
            return MyAjax.upload(file).then(() => {
              return {
                success: 1,
                file: {
                  url: 'https://codex.so/upload/redactor_images/o_e48549d1855c7fc1807308dd14990126.jpg',,
                  // any other image data you want to store, such as width, height, color, extension, etc
                }
              }
            })
          }
        }
      }
    }
  }

  ...
});
byevolution@infinitebrahmanuniverse/nolb-_edi@everything-registry/sub-chunk-277horul-editorhsl-strapi-plugin-react-editorjsgp-editorjs@bigbossstudio/strapi-plugin-editorjs@celmino/sdk-console@celmino/sdk@chizhik/ui-lib@brandontle/react-editor.js@softkit/strapi-plugin-react-editorjs@smileeye.edu.vn/editor@todokek/react-editor.js@carabi/ui@caliobase/caliobase-ui@tienlucky/storage@creators-view/fluid-ui@datahu/client@datahu/component@datahu/designer@culturehacklabs/genki-reloadeddotaila@dicarbene/nuxt3-editorjs@devfamily/admiraldoreacta@emilienkopp/ejs-factory@emilienkopp/html-factory@fakel/rest-admin@highoutput/neyar@fireenjin/editor@hyype-inc/widget@itfin/components@wulperstudio/wulper-studio-editorexchange-react-uidsstudio-editorjseditorjs-imageeditorjs-reacteditorjs-vueeditor-js-componentnuxt3-editorjsnext-step-projectquickvue-editorjssarman-vue-editor-jsui-duckstd-pagestrapi-plugin-editorstrapi-plugin-editorjsstrapi-plugin-editorjs-fieldstrapi-plugin-k-editorjsstrapi-editorjsstrapi-plugin-react-editorjsstrapi-plugin-react-editorjs-extended-embedstrapi-academy-plus-editorjsuse-editor-jssmart-editor@techdemocrat/fluid-ui@acf-int/strapi-plugin-editorjs@acf-int/strapi-plugin-react-editorjs@4kda/vuetify-cifrum-demo-app@ajite/editorjs-image-editor@virtual-spirit/vspace-labs@vt7/vue-editor@keystonejs-contrib/fields-editorjs@zdzcode/zc-web-vuejs-core@zalastax/nolb-_edi@kaniyarasu/react-editor.jsall-in-one-editorjs@madnesslabs/enjin-editor@mohamed-karawia/librarybyevolution-componentsblock-article-js@oak-digital/strapi-plugin-react-editorjs@om-mediaworks/shacl-form@rjgf/rj-components@rypock/react-frontend@rainyland-dev/strapi-plugin-editorjs@realmocean/sdk@realmocean/editor@questflow/canvas
2.9.0

6 months ago

2.8.2

7 months ago

2.8.1

1 year ago

2.8.0

1 year ago

2.7.1

1 year ago

2.7.0

1 year ago

2.6.2

2 years ago

2.6.1

3 years ago

2.6.0

4 years ago

2.5.0

4 years ago

2.4.2

4 years ago

2.4.1

4 years ago

2.4.0

4 years ago

2.3.5

4 years ago

2.3.4

4 years ago

2.3.3

5 years ago

2.3.2

5 years ago

2.3.1

5 years ago

2.3.0

5 years ago

2.2.0

5 years ago

2.1.2

5 years ago

2.1.1

5 years ago

2.1.0

5 years ago