I am using jQuery Dropzone js plugin in one of my projects and I would like to know how can I force it to allow only one file upload at a time.
I know about maxFiles attribute, but what I need is that only one file should be there in Drag and drop area, if i upload another file, last one should be automatically removed.
Here is my current code
var currentFile = null;
Dropzone.autoDiscover = false;
$('#dropzoneForm').dropzone({
//parameter name value
paramName: "files",
autoProcessQueue: false,
maxFiles: 1,
addRemoveLinks: true,
dictResponseError: 'Server not Configured',
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg",// use this to restrict file type
init: function () {
var submitButton = document.querySelector("#SaveImage");
var dropzoneForm = this;
submitButton.addEventListener("click", function () {
dropzoneForm.processQueue();
});
this.on("addedfile", function (file) {
if (currentFile) {
currentFile.previewElement = null;
this.removeFile(currentFile);
}
currentFile = file;
});
this.on("success",
function (file) {
var res = eval('(' + file.xhr.responseText + ')');
dropzoneForm.removeFile(file);
$("#modalUploadPic").modal('hide');
window.location = res.newurl;
});
}
});
Above code works fine's, but It shows more than one files in drag and drop area, if I click upload it uploads the last file selected.
Basically, you need to remove the first/last file placed in dropzone using jQuery and show the new one only, this can be done using the following script in Dropzone js init:
init: function () {
var submitButton = document.querySelector("#SaveImage");
var dropzoneForm = this;
submitButton.addEventListener("click", function () {
dropzoneForm.processQueue();
});
//this function check if there is an file already uploaded
// if yes it removes the first/last file
this.on("addedfile", function (file) {
if (this.files[1] != null) {
this.removeFile(this.files[0]);
}
});
this.on("success",
function (file) {
dropzoneForm.removeFile(file);
});
}
Using the above function will work.
You can also try the below Javascript code
Dropzone.options.YourDropZoneId= {
maxFiles: 1,
accept: function(file, done) {
console.log("uploaded");
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("Only one file is allowed");
});
}
};
Considering HTML form code as below
<form class="dropzone" id="YourDropZoneId"></form>
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly