gpt4 book ai didi

javascript - 使用文件上传最大大小事件的代码到简单代码

转载 作者:行者123 更新时间:2023-11-30 14:56:19 25 4
gpt4 key购买 nike

我是 jquery/javascript 的新手,现在我有一个表单,用户可以在其中上传多个文件,它工作得很好,但我需要对其进行更改,这是工作代码。

$('#userFiles').change(function() {
var combinedSize = 0;
for (var i = 0; i < this.files.length; i++) {
combinedSize += (this.files[i].size || this.files[i].fileSize);
}
if (combinedSize > 104857600) {
toastr["error"]("Max upload size is 100MB");
}
});

HTML

<input type="file" class="form-control" id="userFiles" name="userFiles[]" multiple/>

现在我想做的是在提交之前检查集体文件大小是否超过 100,如果是,则停止提交表单并显示一个错误,你不能上传超过 100MB 现在这是更新的代码。

$("form").on("submit", function(e) {
e.preventDefault();

$('#userFiles').change(function() {
var combinedSize = 0;
for (var i = 0; i < this.files.length; i++) {
combinedSize += (this.files[i].size || this.files[i].fileSize);
}
if (combinedSize > 104857600) {
toastr["error"]("Max upload size is 100MB");
}
});
});

我的问题是它使用 this 函数,因为它是表单提交时输入更改的事件我不能在其中使用另一个事件我希望逻辑仅适用于表单提交如何我可以用 userFile id 属性替换 this 吗?我尝试了几种方法,但没有用。

最佳答案

function validateMaxFileSize() {
//get the files off of the element
var files = $('#userFiles').prop('files');
var combinedSize = 0;

for (var i = 0; i < files.length; i++) {
combinedSize += (files[i].size || files[i].fileSize);
}
//return true if the max is exceeded
return (combinedSize > 104857600);
}

$('#userFiles').change(function() {
//if the max is exceeded, show toaster
if (validateMaxFileSize()) {
toastr["error"]("Max upload size is 100MB");
}
});

$("form").on("submit", function(e) {
//if the max is exceeded, cancel the submit
if (validateMaxFileSize()) {
e.preventDefault();
toastr["error"]("Max upload size is 100MB");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" class="form-control" id="userFiles" name="userFiles[]" multiple/>

关于javascript - 使用文件上传最大大小事件的代码到简单代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47231636/

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