Dropzone.js remove files after an event is fired - javascript

so heres my code:
Dropzone.options.myDropzone = {
// Prevents Dropzone from uploading dropped files immediately
autoProcessQueue: false,
init: function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this; // closure
submitButton.addEventListener("click", function() {
myDropzone.processQueue(); // Tell Dropzone to process all queued files.
myDropzone.removeAllFiles();
console.log("a");
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function() {
// Show submit button here and/or inform user to click it.
});
}
};
how can I add removeAllfiles after clicking the upload button. thanks

This should work:
Dropzone.options.myDropzone = {
autoProcessQueue: false,
init: function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this;
submitButton.addEventListener("click", function() {
myDropzone.processQueue();
});
// Execute when file uploads are complete
this.on("complete", function() {
// If all files have been uploaded
if (this.getQueuedFiles().length == 0 && this.getUploadingFiles().length == 0) {
var _this = this;
// Remove all files
_this.removeAllFiles();
}
});
}
};
By using this.on("complete", function() { //Code to be executed }); you are able to execute your code once the files have been uploaded. In your case, you can remove all of the files.

Related

Javascript - How to load content depends on url

I have 2 buttons and when we click it redirects to different pages with window.location.replace and in document ready I put 2 if's for each click button. But what happens is when I click it entry inside both if's and should not.
My click function:
$('a[href="#reception-supplier"]').on('click', function()
{
var type = $(this).attr('data-type');
$.get("/reception-type/"+type, function(data)
{
$('.popup').html('');
$('.popup').append(data);
$('.popup').fadeIn(300);
$('.loading').fadeOut(300);
$('.inputDossie').select2();
$('.enter-reception-order').on('click', function()
{
var supplierId = $('#supplierChoose option:selected').val();
window.location.replace("/reception-order-header-supplier/"+supplierId);
});
});
});
The second function click:
$('a[href="#reception-order"]').on('click', function()
{
$.get("/reception-type/"+type, function(data)
{
$('.popup').html('');
$('.popup').append(data);
$('.popup').fadeIn(300);
$('.loading').fadeOut(300);
$('.input-order').focus();
$('.enter-reception-order').on('click', function()
{
$('.error-message-reception').fadeOut(300);
$('.error-message-reception .error').remove();
var orderId = $('.input-order').val();
$.get("/verify-reception-order/"+orderId, function(validOrder)
{
window.location.replace("/reception-order-header/"+orderId);
});
});
});
});
And in document ready I put this 2 if's:
$(document ).ready(function()
{
if(window.location.href.match('/reception-order-header-supplier/?') !== null)
{
alert('1');
}
if(window.location.href.match('/reception-order-header/?') !== null)
{
alert('2');
}
});
How can I resolve this issue or what are the alternatives?
Thank you

Dropzone.js when removing a mock file created on page load, the default add files message shows

There is a previous unanswered question about this here but no code or answer was provided. I'm hoping providing some code you'll be able to help me out.
Removing any existing file from Dropzone shows dictDefaultMessage
When I load the page I'm adding mock files to the dropzone. When I click remove on one of those files, the default add image text displays in the dropzone even though there are still files present. How does dropzone keep track of the number of files in the drop zone. I've tried directly modifying the myDropzone.files.length property to match the number of mock files but it breaks the dropzone as I've said in the other question. Here is my code for dropzone.
var jsphotos = '#jsphotos';
var mockFiles = [];
Dropzone.autoDiscover = false;
var fileList = new Array;
var fileListCounter = 0;
var photoDropzone = new Dropzone('#photoDropzone', {
url: 'importphotos.cshtml',
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 5, // MB
method: 'post',
acceptedFiles: 'image/jpeg,image/pjpeg',
dictInvalidFileType: 'Files uploaded must be type .jpg or .jpeg',
init: function () {
this.on("addedfile", function (file) {
// remove size
file.previewElement.querySelector('.dz-size').innerHTML = '';
// add custom button
// Create the remove button
var removeButton = Dropzone.createElement('<i class="fa fa-times-circle-o fa-3x removeButton"></i>');
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
this.on("success", function (file, serverFileName) {
file.previewElement.querySelector('.dz-filename').innerHTML = '<span data-dz-name>'+serverFileName+'</span>';
});
this.on("removedfile", function (file) {
//var rmvFile = "";
//for (f = 0; f < fileList.length; f++) {
// if (fileList[f].fileName == file.name) {
// rmvFile = fileList[f].serverFileName;
// fileListCounter--;
// }
//}
//if (rmvFile) {
// $.ajax({
// url: "deletephoto.cshtml",
// type: "POST",
// data: { "fileList": rmvFile }
// });
//}
});
}
});
$('#photoDropzone').sortable({
items: '.dz-preview',
cursor: 'move',
opacity: 0.5,
containment: "parent",
distance: 10,
tolerance: 'pointer',
sort: function (event, ui) {
var $target = $(event.target);
if (!/html|body/i.test($target.offsetParent()[0].tagName)) {
var top = event.pageY - $target.offsetParent().offset().top - (ui.helper.outerHeight(true) / 2);
ui.helper.css({ 'top': top + 'px' });
}
},
update: function (e, ui) {
// do what you want
}
});
if (jsphotos.length > 0) {
var tmpSplit = jsphotos.split(',');
for (i = 0; i < tmpSplit.length; i++) {
if (tmpSplit[i].length > 0) {
mockFiles.push(tmpSplit[i]);
}
}
}
for (i = 0; i < mockFiles.length; i++) {
// Create the mock file:
var mockFile = { name: mockFiles[i]};
// Call the default addedfile event handler
photoDropzone.emit("addedfile", mockFile);
photoDropzone.emit("success", mockFile, mockFile.name);
// And optionally show the thumbnail of the file:
//photoDropzone.emit("thumbnail", mockFile, '#Globals.tempUploadFolderURL' + mockFile.name);
// Or if the file on your server is not yet in the right
// size, you can let Dropzone download and resize it
// callback and crossOrigin are optional.
photoDropzone.createThumbnailFromUrl(mockFile, '#Globals.tempUploadFolderURL' + mockFile.name);
// Make sure that there is no progress bar, etc...
photoDropzone.emit("complete", mockFile);
// If you use the maxFiles option, make sure you adjust it to the
// correct amount:
//var existingFileCount = 1; // The number of files already uploaded
//Dropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
}
//photoDropzone.files.length = mockFiles.length;
After attempting to code a solution that monitored the count manually and modified the value of the default text, I didn't want a hack to modify class names to 'fool' the dropzone into thinking there were files. So I added this
photoDropzone.files.push(mockFile);
just below
photoDropzone.emit("complete", mockFile);
and now dropzone knows how many files it has, and everything functions appropriately. Files pushed into the array do not get resubmitted, it's the same as adding the mock preview originally.

Enable copy and paste files in dropzone.js

I am using dropzone.js. I want to implement the "Copy & Paste" feature in it.
What I tried is:
Inside dropzone.js:
paste: function(e) {
Dropzone.prototype.emit("paste");
}
Dropzone.prototype.paste = function(e) {
var items, _ref;
if ((e != null ? (_ref = e.clipboardData) != null ? _ref.items : void 0 : void 0) == null) {
return;
}
this.emit("paste", e);
items = e.clipboardData.items;
if (items.length) {
return this._addFilesFromItems(items);
}
};
Page level script:
<script>
var dropZone = Dropzone.forElement('#dropzone1');
dropZone.paste();
</script>
The above is not calling paste:function(e){..}
How to rectify it?
If you don't want to use other JS libraries, you can integrate dropzone with a paste event fairly easily by retrieving the data as a file from the paste event:
// create dropzone however you wish
const myDropzone = new Dropzone("div#element", { url: "/path/to/upload"});
// add paste event listener to the page
document.onpaste = function(event){
const items = (event.clipboardData || event.originalEvent.clipboardData).items;
items.forEach((item) => {
if (item.kind === 'file') {
// adds the file to your dropzone instance
myDropzone.addFile(item.getAsFile())
}
})
}
This worked for me. It uses the FileReaderJS wrapper.
As I am not creating the dropzone programatically, I had to store it at runtime with the init() method.
See here for the FileReaderJS part.
var myDropzone;
function checkUploadFile(filename) {
//do some input checking here, if you want
return true;
}
Dropzone.options.FileDropUploadZone = {
paramName: "myDiv",
maxFilesize: 3, // MB
uploadMultiple: true,
addRemoveLinks: true,
acceptedFiles: 'image/*',
maxFiles: 10,
accept: function(file, done) {
if (!checkUploadFile(file.name)) {
done('Invalid file');
myDropzone.removeFile(file);
}
else { done(); }
},
init: function() {
myDropzone = this;
}
};
$(document).ready(function () {
FileReaderJS.setupClipboard(document.body, {
accept: {
'image/*': 'DataURL'
},
on: {
load: function(e, file) {
myDropzone.addFile(file);
}
}
});
});
var myDropzone = new Dropzone(".dropzone", { });
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
// adds the file to your dropzone instance
myDropzone.addFile(item.getAsFile())
}
}
}
Just add this code. Do not declare URL because URL also declared in PHP or coding file, paste this code in view file (HTML, PHP, etc).

processQueue() is not working in multiple uploads

I use dropzone.js for uploading image. I use this code
init: function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this; // closure
submitButton.addEventListener("click", function() {
var e = document.getElementById("test");
var strUser = e.options[e.selectedIndex].value;
if (strUser == 0) {
alert("First name must be filled out");
return false;
}
else
{
myDropzone.processQueue(); // Tell Dropzone to process all queued files.
}
});
}
But My processQueue upload only two image.But if i using auto process then all file uploaded.
I am trying to use this in my processquee function
while (i < parallelUploads) {
if (!queuedFiles.length) {
return;
}
this.processFile(queuedFiles.shift());
i++;
}
Try to set options of your dropzone.js:
parallelUploads: 30,
uploadMultiple: true
in parallelUploads you can set a different value from 1 and higher.
Good day to you.

Dropzone show files exist

I have a problem I am using on my website dropzone.js, but It doesnt work good for me. I have 2 problems. JSON works fine.
In existing files I havent remove button
When I upload by drag and drop it upload file twice
var FormDropzone = function () {
$(function() {
var projectID = $("#projectID").html();
var myDropzone = new Dropzone("#my-dropzone");
$.getJSON('http://'+window.location.hostname+'/project/getFile/'+projectID, function( json ) {
for (var i = 0; i < json.length; i++) {
var mockFile = { name: json[i].name, size: json[i].size };
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, "../../upload_files/project/1/"+json[i].name);
};
})
});
return {
//main function to initiate the module
init: function () {
Dropzone.options.myDropzone = {
init: function() {
this.on("success", function(file, serverFileName) {
FileList = {"serverFileName" : serverFileName, "fileName" : file.name };
});
this.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-sm btn-block'>Remove file</button>");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
var projectID = $("#projectID").html();
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
$.post( "http://"+window.location.hostname+"/project/deleteFile", { file_name: file.name, project_id: projectID, FileList : FileList["serverFileName"]});
// Remove the file preview.
_this.removeFile(file);
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
}
}
}
};
}();
For adding remove button you have to add delete option i.e addRemoveLinks : true to the dropzone object.
just like this one :
Dropzone.options.mysample = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 1, // MB
addRemoveLinks : true,
};

Categories

Resources