只有在TinyMCE中承诺没有被拒绝的情况下,如何提交带有图像上传的表格



我正在制作一个表单,用户将本地文件上传到TinyMCE编辑器,提交表单后,这些文件将被发送到Flask服务器以存储图像文件。为此,我将automatic_uploads设置为false,并且我还使用自定义image_upload_handler

我的问题是,如果其中一个图像太大,比如超过1MB,那么我想拒绝它,不提交表单(但也不重置用户已经写的所有内容(。

处理程序和初始化函数

// Taken from the TinyMCE v6 docs example, but I added image size checking.
const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => {
// Reject any images uploaded that are too big.
var image_size = blobInfo.blob().size;  // size in bytes
var image_name = blobInfo.blob().filename;
var max_size   = 1048576
if( image_size  > max_size ){
reject("File too large! Max 1MB");
return;  // Why isn't this the end of it?
}
const xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '/upload_image');
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: '#content',
height: 500,
plugins: 'advlist auto-link lists link image charmap preview anchor page break wordcount',
toolbar_mode: 'floating',
automatic_uploads: false,
images_upload_handler: example_image_upload_handler,
});

使用uploadImages((提交表单

document.addEventListener("DOMContentLoaded", function() {
const postSubmitButton = document.querySelector(".submit-post");
// Called when form button is submitted.
postSubmitButton.addEventListener("click", function() {
tinymce.activeEditor.uploadImages()
.then(() => {
document.forms[0].submit();  // I want to submit this only if the
});                              // Promise is not rejected.
});
});

如果发布了正常大小的图像,它会提交良好的图像,并且图像会正确上传到服务器。

然而,如果张贴了更大尺寸的图片,即使承诺被拒绝并退回,表格仍然会提交。然后将图像存储为base64。我不知道该怎么阻止。

我对Promises的工作方式完全陌生,对Javascript也相对陌生,所以如果能在这方面提供任何帮助,我将不胜感激。

已解决,但方式俗气。

我使用了一个全局布尔变量来跟踪文件大小是否可以作为提交表单的条件

最新更新