繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM