Important changes to Tiny Cloud pricing > Find out more

Handling image uploads

How to manage asynchronous image uploads.

Contribute to this page

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.

Note: 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(function(success) {
  document.forms[0].submit();
});

Using uploadImages with jQuery

tinymce.activeEditor.uploadImages(function(success) {
  $.post('ajax/post.php', tinymce.activeEditor.getContent()).done(function() {
    console.log("Uploaded images and posted content as an ajax request.");
  });
});

Note: 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.

Note: 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.

Warning: 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

The images_upload_handler 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 four arguments:

  • blobInfo
  • A success callback
  • A failure callback that takes an error message and an optional object containing:
    • remove - Removes the image from the document, defaults to false
  • A progress callback that takes a value between 1 and 100

When this option is not set, TinyMCE utilizes an XMLHttpRequest to upload images one at a time to the server and calls the success callback with the location of the remote image.

Note: To replace the <img> tag’s src attribute with the remote location, please use the success callback defined in the images_upload_handler function with the returned JSON object’s location property.

Type: JavaScript Function

Example: Using images_upload_handler

function example_image_upload_handler (blobInfo, success, failure, progress) {
  var xhr, formData;

  xhr = new XMLHttpRequest();
  xhr.withCredentials = false;
  xhr.open('POST', 'postAcceptor.php');

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

  xhr.onload = function() {
    var json;

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

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

    json = JSON.parse(xhr.responseText);

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

    success(json.location);
  };

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

  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 XMLHttpRequests.

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 Image Tools 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
});

images_dataimg_filter

Important: This option was deprecated with the release of TinyMCE 5.3. images_dataimg_filter may be removed in a future release of TinyMCE.

The images_dataimg_filter option is used to filter <img> elements before they are passed to image_upload_handler or images_upload_url. If the callback function provided returns false for an image, the image will not be uploaded.

Type: JavaScript Function

Example: Using images_dataimg_filter

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  images_upload_url: 'postAcceptor.php',
  images_dataimg_filter: function(img) {
    return !img.hasAttribute('internal-blob');  // blocks the upload of <img> elements with the attribute "internal-blob".
  }
});

Note: The images_dataimg_filter option can also be used to specify a filter predicate function for disabling the logic that converts base64 images into blobs while within the editor. Tiny discourages using images_dataimg_filter for this purpose.

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.

Further reading on CORS

Can't find what you're looking for? Let us know.

Except as otherwise noted, the content of this page is licensed under the Creative Commons BY-NC-SA 3.0 License, and code samples are licensed under the Apache 2.0 License.