I'm using Dropzone.js to upload files. Now I want to check a filed is filled or not, and if it isn't then cancel the upload.
My HTML code:
<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>
My jQuery code:
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
}
});
}
});
How can I cancel the uploading when the #title
's length is 0?
The accepted answer works if you want to remove the file completely; however, if you want to give the user the option to try and submit the same file again without having to re-add it to dropzone, you need to change a few things about how files are processed.
First, you need to set the autoQueue property to false when you initialize your dropzone:
$('.dropzone').dropzone({
autoQueue: false,
/* The rest of your configuration options */
});
This prevents Dropzone from automatically trying to upload every file right after it's added by the user. This means that now you have to actually enqueue the files yourself programmatically, using the following function:
var yourDropzone = $('.dropzone');
yourDropzone.on("addedfile", function(file) {
if (/* some condition is met by your file */) {
yourDropzone.enqueueFile(file);
}
}
This way, whenever the user selects a file for uploading, we can check if some arbitrary condition is met. Only when this is true, we enqueue the file for uploading to the server.
The advantage of this approach is that now we can actually choose when the file gets uploaded, rather than trying to remove it from the queue while Dropzone is trying to send the enqueued files.
This also allows for other fancier features; for instance, adding a button for each file that lets the user choose when to try and upload it.
What about this
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);
}
});
}
});
If the solution of the accepted answer throw this error :
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
Try
myDropzone.on("addedfile", function(file) {
if (/* some condition is NOT met by your file */) {
myDropzone.removeFile(file);
}});
It's a mix between accepted answer and Protossoario's answer. Without queuing the file. The accepted answer is actually throwing this js error in my config.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With