[英]How to cancel/abort upload in Dropzone.js if condition is not fulfilled?
我正在使用Dropzone.js上傳文件。 現在我想檢查一個字段是否已填寫,如果不是,則取消上傳。
我的HTML代碼:
<input type="text" name="title" id="title" placeholder="Type the title of the album">
<form action="file-upload.cgi" enctype="multipart/form-data" class="dropzone" id="dropzoneform"></form>
我的jQuery代碼:
Dropzone.autoDiscover = false;
$('.dropzone').dropzone({
acceptedFiles: 'image/jpeg',
init: function() {
this.on('sending', function() {
if ( $('#title').val().length > 0 ) {
// just start automatically the uploading
} else {
// need a code to cancel the uploading
}
}
}
});
當#title
的長度為0時,如何取消上傳?
如果要完全刪除文件,則接受的答案有效; 但是,如果您希望為用戶提供嘗試再次提交相同文件的選項而無需將其重新添加到dropzone,則需要更改有關文件處理方式的一些內容。
首先,初始化dropzone時需要將autoQueue屬性設置為false:
$('.dropzone').dropzone({
autoQueue: false,
/* The rest of your configuration options */
});
這可以防止Dropzone在用戶添加后立即自動嘗試上傳每個文件。 這意味着現在您必須使用以下函數以編程方式自己將文件排入隊列:
var yourDropzone = $('.dropzone');
yourDropzone.on("addedfile", function(file) {
if (/* some condition is met by your file */) {
yourDropzone.enqueueFile(file);
}
}
這樣,無論何時用戶選擇要上載的文件,我們都可以檢查是否滿足某些任意條件。 只有在這種情況下,我們才會將文件排入上傳到服務器。
這種方法的優點是,現在我們可以實際選擇何時上傳文件,而不是在Dropzone嘗試發送排隊文件時嘗試將其從隊列中刪除。
這也允許其他更高級的功能; 例如,為每個文件添加一個按鈕,讓用戶選擇何時嘗試上傳它。
那這個呢
Dropzone.autoDiscover = false;
$('.dropzone').dropzone({
acceptedFiles: 'image/jpeg',
init: function() {
var that = this;
that.on('sending', function(file) {
if ( $('#title').val().length <= 0 ) {
that.removeFile(file);
}
}
}
});
如果接受的答案的解決方案拋出此錯誤:
InvalidStateError:嘗試使用不可用或不再可用的對象
嘗試
myDropzone.on("addedfile", function(file) {
if (/* some condition is NOT met by your file */) {
myDropzone.removeFile(file);
}});
這是接受的答案和Protossoario的答案之間的混合。 不排隊文件。 接受的答案實際上是在我的配置中拋出這個js錯誤。
當您聲明dropzone時,您也可以捕獲事件“addedfile”,這在發送任何內容之前發生。
示例:
jQuery("#media-uploader").dropzone({
url: your_posting_url,
acceptedFiles: 'image/jpeg',
addedfile:function (file) {
if( your condition ){
// okay !
} else {
// not okay !
this.removeFile(file);
}
},
... etc ...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.