Dropzone, how to not process queue if errors exist - javascript

So I have a form with Dropzone, plus another textarea, which I want to submit - if I insert an oversize file or too many I get the "oversize" error in the preview container, etc. BUT the form continues to process upon button clicking the form submit (due to my listener). How can I only submit if there file size is correct for both files and doesn't exceed max file limit? I can't see a Dropzone event for say "no errors" to add a click event listener - I think I'm close but semi stuck now, I have the below:
$(function() {
var minImageWidth = 300, minImageHeight = 300;
Dropzone.options.jobApplicationUpload = {
autoProcessQueue: false,
addRemoveLinks: true,
uploadMultiple: true,
paramName: 'file',
previewsContainer: '.dropzone-previews',
acceptedFiles: '.pdf, .doc, .docx',
maxFiles: 2,
maxFilesize: 2, // MB
dictDefaultMessage: '',
clickable: '.fileinput-button',
accept: function(file, done) {
done();
},
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
if(myDropzone.files.length > 0) {
$('#job-application-container').hide();
$('#spinner-modal').modal('show');
$('#spinner-modal p').html('<b>Sending your application,</b> please wait...</p>');
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
}
});
this.on("success", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
$('#job-application-container').hide();
console.log('okay' + response);
localStorage['success'] = 'test';
location.reload();
});
}
};
});

If you want to verify dropzone errors, you can check the rejected files that it contains.
A simple example (with restricted for only one file, maxfilesize to 1Mb and use version 4.3.0):
var myDropzone = new Dropzone("div#myDropzone", {
url: "toLoadUrl",
autoProcessQueue: false,
uploadMultiple: false,
maxFiles: 1,
maxFilesize: 1,
init: function() {
this.on("addedfile", function() {
if (this.files[1]!=null){
this.removeFile(this.files[0]);
}
});
}
});
$('#toServerButton').on('click',function(e){
e.preventDefault();
if (myDropzone.files.length == 0){
alert("You should be select any file");
} else if(myDropzone.getRejectedFiles().length > 0) {
alert("The attached file is invalid");
} else {
myDropzone.processQueue();
}
});
I hope that it was useful to you.
Regards, Yecid

Related

dropzone.js options maybe not placed in corret place

I´m using Dropzone.js but my option are not recognized at all. I tried to place the code different places, but I´m not sure where it should be placed. I read that the Dropzone.options must be out of document.ready or it wont work.
<form action="/" method="post" class="dropzone" id="my-dropzone"></form>
<script>
var myDropzone = new Dropzone("#my-dropzone");
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
Dropzone.options.myDropzone = {
paramName: 'photo',
acceptedFiles: '.jpg, .jpeg, .png',
maxFilesize: 1,
init: function() {
this.on("uploadprogress", function(file, progress) {
console.log("File progress", progress);
});
}
}
Maybe you can try this, I hope it helps.
Click here for the JSFiddle Demo.
Other alternative code, click here.
$(function() {
Dropzone.options.myDropzone = {
maxFilesize: 1,
addRemoveLinks: true,
dictResponseError: 'Server not Configured',
acceptedFiles: ".png,.jpg,.jpeg",
init: function() {
var self = this;
// config
self.options.addRemoveLinks = true;
self.options.dictRemoveFile = "Delete";
//New file added
self.on("addedfile", function(file) {
console.log('new file added ', file);
});
// Send file starts
self.on("sending", function(file) {
console.log('upload started', file);
$('.meter').show();
});
// File upload Progress
self.on("totaluploadprogress", function(progress) {
console.log("progress ", progress);
$('.roller').width(progress + '%');
});
self.on("queuecomplete", function(progress) {
$('.meter').delay(999).slideUp(999);
});
// On removing file
self.on("removedfile", function(file) {
console.log(file);
});
}
};
})

Dropzone Success function not working

I am trying to implement Bootstrap Dropzone on a website but I am facing a problem getting the success message. Below is my code.
var mydropzone = new Dropzone("#dropzonejs-example", {
url: "/Home/FilesUpload/",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 10,
addRemoveLinks: true,
init: function() {
this.on("sending", function(file, xhr, formData) {
formData.append("is_visible", $('#is_visible').is(':checked'));
this.removeFile(file);
this.on("success", function(fname) {
console.log("ok");
});
});
},
});
$("#uploadbtn").click(function() {
mydropzone.processQueue();
});
My controller returns a string so I want to catch the string here. How can it be possible or where am I doing the mistake? Please correct my code.

Dropzone.js 5.0 - use existing images and send the data to the server

I have successfully used Dropzone to display existing files from my server. However, when I submit the form, only new files are submitted to the server, so I don't know if the user has deleted any. Essentiall I want to send the data for all the files currently displayed, including the 'mocked' files and the newly uploaded ones.
I am using autoProcessQueue: false so that I can have a separate submit button to send the data to the server.
My Code:
Dropzone.options.createListingForm = {
autoProcessQueue: false,
uploadMultiple: true,
previewsContainer: '.create-listing-form-uploads',
parallelUploads: 100,
maxFiles: 100,
addRemoveLinks: true,
init: function () {
var thisDropzone = this;
var photos = form.data('photos');
$.each(photos, function (key, photo) {
var mockFile = {
name: photo.name,
size: photo.size,
type: photo.type,
accepted: true
};
thisDropzone.files.push(mockFile); // add to files array
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, photo.path);
thisDropzone.emit("complete", mockFile);
});
}
};
form.on('click', '.create-listing-form-save-photos', function () {
$('.dropzone').get(0).dropzone.processQueue();
return false;
});
Thanks to this answer for the first part of my code:
https://stackoverflow.com/a/45701181/5482719
Each time a file (including mock Files) is removed/deleted from the dropzone, the removedfile event is fired.
You could use this event to delete the removed file from your server as follows:
myDropzone.on("removedfile", function(file) {
// 'file' parameter contains the file object.
console.log('Removed File', file);
// Delete file from server
$.ajax({
type: 'POST',
url: 'url/that/handles/delete',
data: {
fileName: file.name,
},
dataType: 'json'
}).done(function (response) {
// check repsonse, notify user
}).fail(function(resp) {
console.log('xhr failed', resp);
}).always(function(resp) {
// do nothing for now
});
});
Hope that helps.

Dropzonejs cannot submit properly

Here is my dropzone config:
var myDropzone = new Dropzone(".myDZ", {
url: $('#form').attr('action'),
previewTemplate: previewTemplate,
uploadMultiple: true,
previewsContainer: "#previews",
clickable: "#fileinput-btn",
autoProcessQueue: false,
init: function() {
var dz = this;
this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
e.preventDefault();
dz.processQueue();
});
}
});
After the submit button is pressed, I can see from the backend that the data was submitted correctly. However, after the backend returns a response, the front end will not react to it. The form page stays the same without displaying the returned message and clicking on the submit button again will not trigger any submit.
I tried this:
this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
e.preventDefault();
dz.processQueue();
document.getElementById("form").submit();
});
}
});
This will force the form to submit twice but display the correct response after the 2nd attempt. This works but feels wrong.
Any suggestions on what might went wrong?
I would agree that submitting it twice is kind of dirty.
You might try to catch your response in a success function because Dropzone is waiting asynchronously.
var myDropzone = new Dropzone(".myDZ", {
url: $('#form').attr('action'),
previewTemplate: previewTemplate,
uploadMultiple: true,
previewsContainer: "#previews",
clickable: "#fileinput-btn",
autoProcessQueue: false,
init: function() {
var dz = this;
this.element.querySelector("button[type=submit]").addEventListener("click", function (e) {
e.preventDefault();
dz.processQueue();
});
},
// Try this success.
success: function (data, response) {
console.log(response);
}
});

DropZone - How to cancel uploading and remove from queue the correct way

I need to alert the user if he's uploading and existing (on the server) file; i've done it on accept function, like this:
var myDropzone = new Dropzone("form#allegati", {
acceptedFiles: "image/*,.docx,application/pdf",
url: "allegati.php", // Set the url,
dictRemoveFileConfirmation: "Sei sicuro?",
maxFilesize: 10,
thumbnailWidth: 80,
thumbnailHeight: null,
parallelUploads: 20,
createImageThumbnails: true,
previewTemplate: previewTemplate,
autoQueue: true, // Make sure the files aren't queued until manually added
previewsContainer: "#previews", // Define the container to display the previews
clickable: ".fileinput-button", // Define the element that should be used as click trigger to select files.
accept: function (file, done) {
var idIncarico = GetURLParameter('idIncarico');
$.ajax({
// AJAX POST TO CHECK IF FILE EXISTS ON THE SERVER (RETURN TRUE/FALSE)
type: 'POST',
url: 'allegati.php?checkExisting=true&id='+idIncarico,
data: { fileName: file.name },
async: false,
dataType: 'json',
success: function(data) {
// ASKS THE USER TO OVERWRITE
if (data) {
var q = confirm("File esistente. Vuoi sovrascrivere?");
if (q == false){
// IF USER CANCEL UPLOAD:
done("no");
} else {
// IF USER CONFIRM UPLOAD:
done();
}
} else {
done();
}
}
});
},
init: function() {
this.on("error", function(file){
// I GET HERE WHEN USER CLICK ON "CANCEL"
console.log(myDropzone);
});
[CUTTED]
Every seems to work except when the user cancel the upload: the queued file stays there.
I should not call removeFile(file) because I have an ajax script, also bound to every single file "delete" button, that removes existing file from the server (because of the same filename)...
Is there a way to remove the rejected one without calling removeFile(file)?
Screenshot attached
Alex

Categories