Handling image uploads

TinyMCE uploads edited images with the image uploader. This complements TinyMCE’s image editing functionality.

Local images that are added through other means are also uploaded using this function, such as images added by drag and drop when using the paste_data_images configuration property, or using the Tiny PowerPaste plugin.

TinyMCE automatically updates the <img> src attribute with the new path to the remote image.

Local images are uploaded to TinyMCE using the editor.uploadImages() function. This functionality makes it possible for users to save their content before all images have completed uploading. If this occurs and no server path to the remote image is available, the images are saved as Base64.

Execute the editor.uploadImages() function before submitting the editor contents to the server to avoid storing the images as Base64. Use a success callback to execute code once all the images are uploaded. This success callback can save the editor’s content to the server through a POST.

Review the examples below:

Using uploadImages and then posting a form

tinymce.activeEditor.uploadImages().then(() => {
  document.forms[0].submit();
});

Using uploadImages with jQuery

tinymce.activeEditor.uploadImages().then(() => {
  $.post('ajax/post.php', tinymce.activeEditor.getContent()).done(() => {
    console.log("Uploaded images and posted content as an ajax request.");
  });
});
SVGs (Scalable Vector Graphics) are not supported in TinyMCE to protect our users and their end-users. SVGs can be used to perform both client-side and server-side attacks.

Image Uploader requirements

A server-side upload handler script uploads local images to a remote server. The script must:

  • Accept the images on the server

  • Store images appropriately

  • Return a JSON object containing the image’s upload location

An example PHP upload handler implementation is available here.

Images are sent to the Image Uploader via HTTP POST with each post containing a single image. The image handler at the URL referenced in the images_upload_url must "store" the image in the application. Some examples include:

  • Store the item in a folder on the web server

  • Store the item on a CDN server

  • Store the item in a database

  • Store the item in an asset management system

Use a standardized name in the post (e.g. blobid0, blobid1, imagetools0, imagetools1) when the image is uploaded.

Ensure that your upload handler script generates a unique name for each uploaded file before storing the image. A common method is to append the current time in milliseconds to the end of the file name. This creates file names such as blobid0-1458428901092.png or blobid0-1460405299-0114.png.
The files will be overwritten if the file names are not unique.

This server-side upload handler script must return a JSON object containing a "location" property. This property represents the remote location and filename of the newly uploaded image.

{ location: '/uploaded/image/path/image.png' }

Image upload options

Set the images_upload_url or images_upload_handler option for image uploads to function. The other options shown here are optional.

Required:

Or

Optional:

images_upload_url

This option lets you specify a URL for the server-side upload handler. Upload will get triggered whenever you call editor.uploadImages() or - automatically, if automatic_uploads option is enabled. Upload handler should return a new location for the uploaded file in the following format:

{ "location": "folder/sub-folder/new-location.png" }

Be sure to checkout a demo implementation of the server-side upload handler here (written in PHP).

Type: String

Example: using images_upload_url

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  images_upload_url: 'postAcceptor.php'
});

images_upload_handler

This option allows you to specify a function that is used to replace TinyMCE’s default JavaScript upload handler function with custom logic.

The upload handler function takes two arguments:

  • blobInfo

  • A progress callback that takes a value between 1 and 100.

and returns a Promise that will resolve with the uploaded image URL or reject with an error. The error can be either a string or an object containing the following properties:

  • message - The error message to display in the UI.

  • remove - A flag to remove the image from the document, defaults to false if not set.

When this option is not set, TinyMCE utilizes an XMLHttpRequest to upload images one at a time to the server and resolves the Promise with the JSON location property for the remote image returned by the server.

Type: Function

Example: using images_upload_handler

const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest();
  xhr.withCredentials = false;
  xhr.open('POST', 'postAcceptor.php');

  xhr.upload.onprogress = (e) => {
    progress(e.loaded / e.total * 100);
  };

  xhr.onload = () => {
    if (xhr.status === 403) {
      reject({ message: 'HTTP Error: ' + xhr.status, remove: true });
      return;
    }

    if (xhr.status < 200 || xhr.status >= 300) {
      reject('HTTP Error: ' + xhr.status);
      return;
    }

    const json = JSON.parse(xhr.responseText);

    if (!json || typeof json.location != 'string') {
      reject('Invalid JSON: ' + xhr.responseText);
      return;
    }

    resolve(json.location);
  };

  xhr.onerror = () => {
    reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
  };

  const formData = new FormData();
  formData.append('file', blobInfo.blob(), blobInfo.filename());

  xhr.send(formData);
});

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  images_upload_handler: example_image_upload_handler
});

images_upload_base_path

This option lets you specify a basepath to prepend to URLs returned from the configured images_upload_url page.

Type: String

Example: using images_upload_base_path

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  images_upload_url: 'postAcceptor.php',
  images_upload_base_path: '/some/basepath'
});

images_upload_credentials

The images_upload_credentials option specifies whether calls to the configured images_upload_url should pass along credentials (such as cookies, authorization headers, or TLS client certificates) for cross-domain uploads. When set to true, credentials will be sent to the upload handler, similar to the withCredentials property of XMLHttpRequest.

Type: Boolean

Default value: false

Possible values: true, false

Example: using images_upload_credentials

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  images_upload_url: 'postAcceptor.php',
  images_upload_credentials: true
});

images_reuse_filename

By default TinyMCE will generate unique filename for each uploaded file (for details refer to Upload Images). Sometimes this might have undesirable side-effects. For example, when automatic_uploads is enabled, every manipulation on the image done with the Enhanced Image Editing plugin, results in file upload and each time under a different filename, despite the fact that the image stays the same.

Setting images_reuse_filename to true tells TinyMCE to use the actual filename of the image, instead of generating a new one each time. Take into account that src attribute of the corresponding <img> tag gets replaced with whatever filename you send back from the server (see images_upload_url). It can be the same filename or something else, but the next time that filename is used for the upload.

Type: Boolean

Default value: false

Possible values: true, false

Example: using images_reuse_filename

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  automatic_uploads: true,
  images_upload_url: 'postAcceptor.php',
  images_reuse_filename: true
});

CORS considerations

Configure Cross-origin resource sharing (CORS) to upload image data to a separate domain and to comply with JavaScript "same origin" restrictions.

CORS maintains stringent rules about what constitutes a cross-origin request. The browser can require CORS headers when uploading to the same server the editor is hosted on. For example:

  • A different port on the same domain name

  • Using the host IP address instead of the domain name

  • Swapping between HTTP and HTTPS for the page and the upload script

The upload script URL origin must exactly match the origin of the URL in the address bar, or the browser will require CORS headers to access it. Use a relative URL to specify the script address instead of an absolute one to guarantee this.

All supported browsers print messages to the JavaScript console if there is a CORS error.

The PHP Upload Handler Script provided here configures CORS in the $accepted_origins variable. Configure CORS at the web application layer or the HTTP server layer.