TinyMCE:在图像上传时显示错误消息

时间:2017-04-17 19:08:48

标签: javascript php tinymce tinymce-4

我能够实现TinyMCE文档中的图像上传示例:

https://www.tinymce.com/docs/advanced/php-upload-handler/

我的问题是如何在发生错误时向用户显示特定的错误消息?例如,如果我上传了无效的文件类型,它只会显示如下的通用500错误消息:

enter image description here

如何向用户显示更具体的错误消息,例如 “无效的扩展程序”?

1 个答案:

答案 0 :(得分:1)

您需要编写自定义images_upload_handler。 在设置中添加以下行:

images_upload_handler : function handler(blobInfo, success, failure, progress) {
{
        var valid_extensions = ['png','jpg']
        var ext, extensions;

        extensions = {
          'image/jpeg': 'jpg',
          'image/jpg': 'jpg',
          'image/gif': 'gif',
          'image/png': 'png'
        };
        ext = extensions[blobInfo.blob().type.toLowerCase()] || 'dat';
        //add your extension test here.
        if( valid_extensions.indexOf(ext) == -1){
             failure("Invalid extension");
                return;
        }

        var xhr, formData;

        xhr = new XMLHttpRequest();
        xhr.open('POST', settings.url);
        xhr.withCredentials = settings.credentials;

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

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

        xhr.onload = function() {
            var json;

            if (xhr.status != 200) {
                failure("HTTP Error: " + xhr.status);
                return;
            }

            json = JSON.parse(xhr.responseText);

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

            success(pathJoin(settings.basePath, json.location));
        };

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

        xhr.send(formData);
    }
}