Tinymce限制图片上传大小(超过1M提示并可重新选择)
Tinymce限制图片上传大小,超过1M提示并可重新选择上传
在使用Tinymce富文本编辑器时,限制图片上传大小可以有效地控制服务器资源的占用。本文将介绍如何利用Tinymce的 image_uploadtab 钩子来实现图片大小限制,并在上传图片超过限制时进行友好提示,方便用户重新选择。
以下是完整的代码示例:
tinymce.init({
selector: 'textarea',
plugins: 'image',
toolbar: 'image',
images_upload_handler: function (blobInfo, success, failure) {
if (blobInfo.blob().size > 1048576) { // 1MB
alert('文件大小超过1MB限制,请重新选择图片!');
return;
}
// 继续图片上传逻辑
},
setup: function (editor) {
editor.on('preInit', function () {
editor.ui.registry.addButton('image', {
icon: 'image',
tooltip: '插入图片',
onAction: function () {
editor.execCommand('mceInsertContent', false, '<img src=""/>');
editor.windowManager.open({
title: '插入图片',
body: [
{
type: 'textbox',
name: 'src',
label: '图片地址',
autofocus: true,
onchange: function () {
var input = this;
var value = input.value();
if (value && value.length > 0) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', value, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
input.parent().find('#size').text(' (' + formatBytes(xhr.getResponseHeader('Content-Length')) + ')');
} else {
input.parent().find('#size').text('');
}
}
};
xhr.send();
} else {
input.parent().find('#size').text('');
}
}
},
{
type: 'label',
name: 'size',
label: '',
text: ''
}
],
onsubmit: function (e) {
var src = e.data.src;
if (src && src.length > 0) {
if (src.indexOf('data:image') === 0) {
editor.execCommand('mceInsertContent', false, '<img src='' + src + ''/>');
} else {
var xhr = new XMLHttpRequest();
xhr.open('GET', src, true);
xhr.responseType = 'blob';
xhr.onload = function () {
if (xhr.status === 200) {
var blob = xhr.response;
if (blob.size > 1048576) { // 1MB
alert('文件大小超过1MB限制,请重新选择图片!');
return;
}
var reader = new FileReader();
reader.onload = function () {
var dataUrl = reader.result;
editor.execCommand('mceInsertContent', false, '<img src='' + dataUrl + ''/>');
};
reader.readAsDataURL(blob);
}
};
xhr.send();
}
}
}
});
}
});
});
}
});
function formatBytes(bytes, decimals) {
if (bytes === 0) return '0 Bytes';
var k = 1024,
dm = decimals || 2,
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
代码解释:
images_upload_handler钩子: 这段代码的核心是images_upload_handler钩子函数。它会在图片上传前被调用,并接收上传图片的信息。- 文件大小检查: 在
images_upload_handler函数中,我们首先检查上传图片的大小是否超过了预设的限制 (这里设置为 1MB)。 - 提示信息: 如果图片大小超过限制,我们会使用
alert()函数弹出提示框,告知用户文件过大。 - 重新选择:
return;语句会阻止图片的上传,并允许用户重新选择符合要求的图片。
通过以上代码,我们成功地为Tinymce编辑器添加了图片上传大小限制的功能,并在上传失败时提供了清晰的提示信息。这有助于提升用户体验,并减轻服务器端的压力。
原文地址: https://www.cveoy.top/t/topic/jvFR 著作权归作者所有。请勿转载和采集!