Tinymce - images_upload_handler - Validate max file size
Asked Answered
J

2

5

Is there any way to validate the image file size in the images_upload_handler of Tinymce 5.

tinymce.init({
        selector: '#mytextarea',
    images_upload_handler: function(blobInfo, success, failure) {
      .......
    }
});

The function has 3 arguments, First one is the blob content of the selected image. There is no provision to check the size of the blob content.

Is there any way?

Jonijonie answered 13/1, 2020 at 12:22 Comment(0)
L
8
blobInfo.blob().size

gives the size of the uploaded image in bytes and, the failure raises an error : Failed to upload image : ...

The function triggers every time an image is uploaded, pasted or edited in the editor.

This code raises an error while the uploaded or edited image is larger than max_size

images_upload_handler: function (blobInfo, success, failure) {
    var image_size = blobInfo.blob().size / 1000;  // image size in kbytes
    var max_size   = max_size_value                // max size in kbytes
    if( image_size  > max_size ){        
        failure('Image is too large( '+ image_size  + ') ,Maximum image size is:' + max_size + ' kB');
        return;      
    }else{
        // Your code
    }
Lowborn answered 19/5, 2020 at 12:7 Comment(3)
When I do this, the image still shows up in the editor. how can I prevent the image from showing there?Cathay
@Cathay tinymce documents says that failure has an optional object remove that removes the uploaded image if it sets to true and by default it is false. however it seems that it doesn't work with upload image from quickbar plugin and just work with upload from insert in toolbar menu.failure('a message', {remove:true})Lowborn
This does not work with HUGE files of which the user does not know about the size. The server rejects it anyway with a popup 'File could not be read' or an empty popup in the TinyMCE file upload popup. This should be handles SERVER side.Christychristye
C
4

In TinyMCE v6:

const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {

  // In case which the max file size is 1Mb
  if (blobInfo.blob().size > 1024 * 1024) {
    return reject({message: 'File is too big!', remove: true});
  }

  // Do the rest
});

tinymce.init({
  selector: 'textarea',
  images_upload_handler: example_image_upload_handler
});

For how to send the POST request, see https://www.tiny.cloud/docs/tinymce/6/upload-images/#example-using-images_upload_handler.

Cybernetics answered 2/11, 2022 at 1:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.