如果条件不满足,如何在Dropzone.js中取消/中止上传?

我正在使用Dropzone.js上传文件。 现在我想检查一个字段是否已填写,如果不是,则取消上传。

我的HTML代码:

 

我的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.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); } } } }); 

如果要完全删除文件,则接受的答案有效; 但是,如果您想让用户选择尝试再次提交同一文件而无需将其重新添加到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尝试发送排队文件时尝试将其从队列中删除。

这也允许其他更高级的function; 例如,为每个文件添加一个按钮,让用户选择何时尝试上传它。

如果接受的答案的解决方案抛出此错误:

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 ... });