有点晚了,但也许其他人需要这个。
那么,您需要在 init 函数中创建一个新变量“totalSize”。
在文件中添加一个事件监听器以增加大小和另一个用于子结构,然后在您发送请求以显示错误之前进行一点控制,我的英语不好,所以这里是一个例子:
...
init: function() {
var totalsize = 0.0;
...
this.on("addedfile", function(file) {
...
// increment total size when we add a file (in Mb)
totalsize += parseFloat((file.size / (1024*1024)).toFixed(2));
//substruct the size of the removed file
removeButton.addEventListener("click", function(e) {
...
_this.removeFile(file);
totalsize -= parseFloat((file.size / (1024*1024)).toFixed(2));
...
});
...
});
//and an event for the submission to controle before submit don't forget to prevent default
this.on("sendingmultiple", function(data, xhr, formData) {
if (totalsize <= 20) {
//do the request
}else { // else show the error
$('#error').show();
$('#error').text('Oooops ! total files size must be less then 20Mb');
}
});
}
也许不是很清楚,所以有一个完整的代码示例,在我的代码中我添加了一个样式删除按钮,所以不要忘记删除它:
init: function() {
var totalsize = 0.0;
dzClosure = this; // Makes sure that 'this' is understood inside the functions below.
// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement("<a href='javascript:;'' class='btn red btn-sm btn-block'>Remove</a>");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
totalsize -= parseFloat((file.size / (1024*1024)).toFixed(2));
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
//increment
totalsize += parseFloat((file.size / (1024*1024)).toFixed(2));
});
//send all the form data along with the files:
this.on("sendingmultiple", function(data, xhr, formData) {
if (totalsize <= 20) {
console.log(totalsize);
//u can append formData here too
formData.append("something", jQuery("#something").val());
}else {
$('#error').show();
$('#error').text('Oooops ! total files size must be less then 20Mb');
}
});
}