gpt4 book ai didi

javascript - 为我的 XMLHttpRequest 文件上传添加文件大小限制

转载 作者:行者123 更新时间:2023-12-02 15:00:08 27 4
gpt4 key购买 nike

我在我的应用程序中使用 Trix ( https://github.com/basecamp/trix ) 作为文本编辑器,并允许通过那里上传文件。我想在上传时添加最大 5mb 的文件大小,但我不知道如何操作。您将如何实现它?

(function() {
var createStorageKey, host, uploadAttachment;

document.addEventListener("trix-attachment-add", function(event) {
var attachment;
attachment = event.attachment;
if (attachment.file) {
return uploadAttachment(attachment);
}
});

host = "https://my.cloudfront.net/";

uploadAttachment = function(attachment) {
var file, form, key, xhr;
file = attachment.file;
key = createStorageKey(file);
form = new FormData;
form.append("key", key);
form.append("Content-Type", file.type);
form.append("file", file);
xhr = new XMLHttpRequest;
xhr.open("POST", host, true);
xhr.upload.onprogress = function(event) {
var progress;
progress = event.loaded / event.total * 100;
return attachment.setUploadProgress(progress);
};
xhr.onload = function() {
var href, url;
if (xhr.status === 204) {
url = href = host + key;
return attachment.setAttributes({
url: url,
href: href
});
}
};
return xhr.send(form);
};

createStorageKey = function(file) {
var date, day, time;
date = new Date();
day = date.toISOString().slice(0, 10);
time = date.getTime();
return "tmp/" + day + "/" + time + "-" + file.name;
};

}).call(this);

最佳答案

您应该在客户端和服务器端执行此操作。对于客户端,只需添加一个条件,如下所示:

file = attachment.file;
if (file.size == 0) {
attachment.remove();
alert("The file you submitted looks empty.");
return;
} else if (file.size / (1024*2)) > 5) {
attachment.remove();
alert("Your file seems too big for uploading.");
return;
}

你也可以看看我写的这个要点,显示了完整的实现:https://gist.github.com/pmhoudry/a0dc6905872a41a316135d42a5537ddb

关于javascript - 为我的 XMLHttpRequest 文件上传添加文件大小限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486142/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com