DropzoneJS: Prevent uploading and displaying unsupported files - javascript

For my project I'm using the Drag & Drop library DropzoneJS. It's working nicely, but I want to have a specific functionality that (for as far as I can see) is not supported 'out of the box'.
In my Dropzone config I've specified the acceptedFiles:
acceptedFiles: ".png,.jpg,.jpeg,.gif,.pdf"
When I use the browse button it automatically checks if the file is supported or not. But when I drag & drop files, the check is done AFTER the upload has already been done, and displays the file with an error message.
What I'd like to achieve is that the drag & drop first checks if the files are supported, and automatically discard the unsupported file. I'd still like to display an error message which states that some of the files are not supported.
For reference, here is my complete Dropzone config:
import Dropzone from 'dropzone';
export default class UI_DropZone {
constructor() {
if (document.querySelector('#dropZone')) {
let previewNode = document.querySelector("#template");
previewNode.id = "";
let previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
return new Dropzone("#dropZone", {
url: "/dist/files",
thumbnailWidth: 300,
thumbnailHeight: 300,
parallelUploads: 20,
maxFilesize: 10,
acceptedFiles: ".png,.jpg,.jpeg,.gif,.pdf",
previewTemplate: previewTemplate,
previewsContainer: '#previews',
clickable: '.fileinput-button',
autoProcessQueue: false
});
}
}
}

You can catch errors and remove the file with some sort of notification if it is a problem:
init: function() {
this.on("error", function(file, message, xhr) {
if (xhr == null) this.removeFile(file); // perhaps not remove on xhr errors
alert(message);
});
}
So with your config this will look like:
return new Dropzone("#dropZone", {
url: "/dist/files",
thumbnailWidth: 300,
thumbnailHeight: 300,
parallelUploads: 20,
maxFilesize: 10,
acceptedFiles: ".png,.jpg,.jpeg,.gif,.pdf",
previewTemplate: previewTemplate,
previewsContainer: '#previews',
clickable: '.fileinput-button',
autoProcessQueue: false,
"error": function(file, message, xhr) {
if (xhr == null) this.removeFile(file); // perhaps not remove on xhr errors
alert(message);
}
});
Example: https://jsfiddle.net/m4ye8gL2/1

myDropzone.on("error", function(file, message, xhr) {
if(xhr == null) myDropzone.removeFile(file);
alert(message)
});

Related

Sorting Dropzone.js

I'm using Dropzone.js with Spring boot.
Everything works fine except, when I upload image it goes on the bottom of gallery.
How can I make it so that the image which is uploaded shows first (on the top of gallery). Does Dropzone have some built in methods that I could use?
var extraImageDropzone = new Dropzone('#extraImagesDropzone', {
url: "/uploads/upload",
maxFiles: 25,
acceptedFiles: 'image/*',
autoQueue: true,
addRemoveLinks: false,
parallelUploads: 1,
createImageThumbnails: false,
createImageData:false,
previewsContainer: null,
previewTemplate: '<li style="diplay:none"></li>',
hiddenInputContainer: "#extraImagesDropzoneToggle",
clickable: "#extraImagesDropzoneToggle",
// thumbnailWidth: 100,
thumbnailHeight: 100,
thumbnailMethod: `contain`,
complete: function(file, response) {
console.log('completed');
},
success: function(f, response) {
if (response.id) {
console.log('File uploaded' + response.URL);
$(".image-picker").data('picker').append_one(response.id, response.URL);
} else {
alert('Error while uploading');
this.removeFile(f);
}
}
});
Added prepend_one method to Image-picker lib and now works fine.
ImagePicker.prototype.prepend_one = function (val, image_src) {
var option = jQuery('<option>').val(val).attr('data-img-src', image_src);
this.select.prepend(option);
var picker_option = new ImagePickerOption(option[0], this, this.opts);
this.picker_options.push(picker_option);
this.picker.prepend(picker_option.node);
};

Can I add/remove the inputs one by one? - dropzone.js

Can I add/remove the inputs one by one?
The input should only post the currently selected array of files.
I am using dropzone.js for my current project and dropzone.js does not help to append file as HTML file input and how I can post image files when post data.
This is my script:
var myDropzone = new Dropzone("#filedrag",{
url: "upload", // Set the Upload Url
parallelUploads: 5,
thumbnailWidth: 600,
thumbnailHeight: 600,
acceptedFiles:"image/*",
previewTemplate: previewTemplate,
maxFiles: 20,
previewsContainer: "#previews",
clickable: ".fileinput-button",
init: function() {this.on("success", function(file, response) {
});
this.on("addedfile", function(file) {
});
}
});

Dropzone - How to remove files?

how can I remove the uploaded files and previewed thumbnails? That´s my code.
The alert works, but the thumbs are not hiding.
new Dropzone("form#galerie", {
url: "/business/kleinanzeigen/upload",
maxFilesize: 5,
maxFiles: 10,
acceptedFiles: '.png, .gif, .jpg',
complete: function (success) {
vm.form.galerie.push(JSON.parse(success.xhr.response))
},
addRemoveLinks: true,
removedfile: function (file) {
//console.log(file);
alert('works');
this.removeFile(file);
}
}
);
Your removedFile function doesn't seem right. It should be something like this:
removedfile: function(f) {
var reference;
return (reference = f.previewElement) != null ? reference.parentNode.removeChild(f.previewElement) : void 0;
}

Dropzone, how to not process queue if errors exist

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

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