On successmultiple function in Dropzone.js - javascript

I'm trying to alert the user when their files have been successfully uploaded but am stuck on getting it to work after the init function.
Here is my script:
<script>
Dropzone.options.myDropzone = {
paramName: 'file',
maxFilesize: 10, // MB
maxFiles: 20,
acceptedFiles: ".jpeg,.jpg,.png,.gif,.pdf,.doc,.docx,.xlsx,.xls",
};
this.on("successmultiple", function (file) {
alert("All files have uploaded ");
});
</script>
The upload does work so I am assuming it is how I am calling the successmultiple portion.

I ended up realizing that I needed to use: queuecomplete rather, which was the more appropriate option instead. (See: http://www.dropzonejs.com/#events)

Related

DropZone JS not grabbing external value from input field called by jQuery ID

I am experiencing an issue with DropZone JS Grabbing an input value and passing it along to the upload script. The upload is working and everything is fine EXCEPT this field not sending in the POST.
I have a very basic DZ config:
$("#file_uploader").dropzone({
url: '/ajax/upload.php',
dictDefaultMessage: 'Drop photos or click here to upload',
maxFilesize: 400000,
params: {'project': $('#project-name').val()}, // This is the part I am having issues with
success: function (file, response) {
var obj = JSON.parse(response);
if (obj.status === 'success') {
console.log('gtg');
} else {
alert('upload failed');
$(".dz-preview").remove();
}
}
});
I have a field in my html that looks like:
<input type="text" id="project-name" required="required"
class="form-control col-md-6 col-xs-12 limited_form"
placeholder="Project Name">
If I simply overwrite 'project': $('#project-name').val() to look like:
'project': 'test'
It works. So it's a matter of Dropzone not being able to "see" that input field for some reason.
I thought it might be the dash in the id project-name -- But according to the rules in HTML5 dashes are allowed in Ids.
There are no errors in the console, and this:
// Testing if Selector is working
$(document).on('keyup', '#project-name', function () {
console.log( $('#project-name').val() );
});
displays the project-name contents in the console correctly as I type them, so I know my selector is OK. Thus, my confusion on why DropZone isn't "seeing" it.
Why is DropZone "ignoring" my jQuery identified by selector id? Am I missing something glaringly wrong?
UPDATE
It is worth noting that my config lies within a $(document).ready(function () { -- However I have tried it both inside, and outside the function and still the problem persists.
Your dropzone script was probably trying to retrieve the value before the element is loaded on the DOM. Loading your script inside a $( document ).ready() function would be one way to go about it. Another way would be to just assign the script to a variable and then referencing the variable in dropzone like this:
$("#file_uploader").dropzone({
url: '/ajax/upload.php',
dictDefaultMessage: 'Drop photos or click here to upload',
maxFilesize: 400000,
params: {'project': function() {
var x = $('#project-name').val();
return x;
}},
success: /* some function */
});
You can also try to directly return the input value within the function and see if that works.
$("#file_uploader").dropzone({
url: '/ajax/upload.php',
dictDefaultMessage: 'Drop photos or click here to upload',
maxFilesize: 400000,
params: {'project': function() {
return $('#project-name').val();
}},
success: /* some function */
});

Dropzone JS Global Events

I might have this wrong but Dropzone JS seems to do things in a very odd way. http://www.dropzonejs.com/#events
This is the recommended method of adding an event
Dropzone.options.myAwesomeDropzone = {
init: function() {
this.on("addedfile", function(file) { alert("Added file."); });
}
};
This assumes you know what myAwesomeDropzone is. But if you create them programatically then you may not know what myAwesomeDropzone is. It could be anything, e.g. if you have three different Dropzones on the page based on some ID then the identifier won't be myAwesomeDropzone or even guessable.
It would be handy to be able to do
$(".dropzone").on("addedfile", function(file) {
alert("hello");
});
But it does not work. I just want to be able to attach a global event to all my dropzones.
If you have several dropzones in the same page, and you need for each one to have a different configuration, you have to initialize each one separately.
As I see you are using jQuery know that you can also initialize the dropzone elements using the Dropzone jQuery plugin already included in dropzone.
As example imagine that each dropzone accepts a different file type:
Dropzone.autoDiscover = false;
$("#dropzone1").dropzone({
url: 'urlForDropzone1.php',
acceptedFiles: 'application/pdf',
init: function(){
this.on("addedfile", function(file) {
alert("Added" + file.name + " on Dropzone 1.");
}),
this.on("success", function(file) {
alert(file.name " Uploaded from Dropzone 1")
})
}
});
$("#dropzone2").dropzone({
url: 'urlForDropzone2.php',
acceptedFiles: 'image/*,.jpeg,.jpg,.png,.gif',
init: function(){
this.on("addedfile", function(file) {
alert("Added" + file.name + " on Dropzone 2.");
}),
this.on("success", function(file) {
alert(file.name " Uploaded from Dropzone 2")
})
}
});
Notice that first you need to disable the autodiscover feature, then initialize each dropzone separately, the url are optional, don't need to include them if you already have them in the html.
You can append dropzone very similar as in your 2nd snippet. When you attach the configuration directly when initializing the dropzone.
new Dropzone(".dropzone", {
url: 'someUrl',
addedfile: function () {
alert('Hallo');
}
});
The below works, my issue was that I had dropzone.js included twice which made Dropzone.autoDiscover = false; be ignored.
Dropzone.autoDiscover = false;
$(".dropzone").on("addedfile", function(file) {
alert("hello");
});

jquery file upload not resizing images client side when using send

I'm using jquery file upload in conjunction with summernote to upload images. I know jquery file-upload is supposed to re size large images to a max of 1920 x 1080 as a default but this isn't happening in my case. Here's my current setup:
$('#summernote').summernote({
height: 500,
minHeight: 300,
onImageUpload: function(files, editor, welEditable) {
uploadFile(files, editor, welEditable);
}
});
$('#fileupload').fileupload({
url: site_root + '/photos/index.php',
dataType: 'json',
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
maxFileSize: 8000000,
imageMaxWidth: 1920,
imageMaxHeight: 1080,
imageCrop: true
});
function uploadFile(files, editor, welEditable) {
if (files == null) {
return;
}
$('#fileupload').fileupload('send', {files: files})
.success(function (result, textStatus, jqXHR) {
//
});
});
}
I've even added image maxWidth/Height params but the images fail to be re sized. The image sizing works when I use jquery file upload in other areas but when using the send call it fails to resize them.
Is this a bug or am I missing something obvious?
Thanks,
-Paul
Are you including the extra required JS files listed on here?
https://github.com/blueimp/jQuery-File-Upload/wiki/Client-side-Image-Resizing
If so, it looks like you need to set "disableImageResize: false"

Add existing image files in Dropzone

I am using Dropzonejs to add image upload functionality in a Form, as I have various other fields in form so I have set autoProcessQueue to false and Processing it on click on Submit button of Form as shown below.
Dropzone.options.portfolioForm = {
url: "/user/portfolio/save",
previewsContainer: ".dropzone-previews",
uploadMultiple: true,
parallelUploads: 8,
autoProcessQueue: false,
autoDiscover: false,
addRemoveLinks: true,
maxFiles: 8,
init: function() {
var myDropzone = this;
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
});
}
}
This works fine and allows me to process all images sent when form is submitted. However, I also want to be able to see images already uploaded by user when he edits the form again. So I went through following post from Dropzone Wiki.
https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-files-already-stored-on-server
Which populates dropzone-preview area with existing images but it does not send existing images with form submit this time. I guess this is because theses images are not added in queue but If it's so then how can update on server side, In case an existing image is removed by user?
Also, what would be the better approach, add already added images in queue again or just send information of removed file?
I spent a bit of time trying to add images again, but after battling with it for a while I ended up just sending information about the deleted images back to the server.
When populating dropzone with existing images I attach the image's url to the mockFile object. In the removedfile event I add a hidden input to the form if the file that is being removed is a prepopulated image (determined by testing whether the file that is passed into the event has a url property). I have included the relevant code below:
Dropzone.options.imageDropzone = {
paramName: 'NewImages',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
init: function () {
var myDropzone = this;
//Populate any existing thumbnails
if (thumbnailUrls) {
for (var i = 0; i < thumbnailUrls.length; i++) {
var mockFile = {
name: "myimage.jpg",
size: 12345,
type: 'image/jpeg',
status: Dropzone.ADDED,
url: thumbnailUrls[i]
};
// Call the default addedfile event handler
myDropzone.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
myDropzone.emit("thumbnail", mockFile, thumbnailUrls[i]);
myDropzone.files.push(mockFile);
}
}
this.on("removedfile", function (file) {
// Only files that have been programmatically added should
// have a url property.
if (file.url && file.url.trim().length > 0) {
$("<input type='hidden'>").attr({
id: 'DeletedImageUrls',
name: 'DeletedImageUrls'
}).val(file.url).appendTo('#image-form');
}
});
}
});
Server code (asp mvc controller):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel viewModel)
{
if (ModelState.IsValid)
{
foreach (var url in viewModel.DeletedImageUrls)
{
// Code to remove the image
}
foreach (var image in viewModel.NewImages)
{
// Code to add the image
}
}
}
I hope that helps.
To extend on Teppic's answer, I found you needed to emit the complete event to remove the progress bar on the preview.
var file = {
name: value.name,
size: value.size,
status: Dropzone.ADDED,
accepted: true
};
myDropzone.emit("addedfile", file);
myDropzone.emit("thumbnail", file, value.path);
myDropzone.emit("complete", file);
myDropzone.files.push(file);
just use myDropzone.addFile(file)
from dropzone source code https://github.com/enyo/dropzone/blob/4e20bd4c508179997b4b172eb66e927f9c0c8564/dist/dropzone.js#L978
There's an official FAQ for that here
I solved this using the dropzone's built in "displayExistingFile" method.
in your init: function.
Create the mockfile
let mockFile = { name: file.title, size: file.size, dataURL:};
Call the displayExistingFile function
this.displayExistingFile(mockFile, , null, 'anonymous')
Instead of 'null' you can place a callback to respond to the thumbnail load event.
The 'anonymous' is for the cross origin property.
Originally I was doing this to programmatically upload a pre-existing file:
myDropzone.emit("addedfile", imageFile);
myDropzone.emit("thumbnail", imageFile, imageUrl);
myDropzone.files.push(file);
However, referencing this Dropzone Github Issue I found an easier way to directly upload:
myDropzone.uploadFiles([imageFile])
Unfortunately there are no references to this uploadFiles method in the Dropzone Documentation, so I figured I'd share some knowledge with all you Dropzone users.
Hope this helps someone
If you have the URL of the file, you can add the file with addFile.
fetch("url")
.then(res => res.blob())
.then((currentBlob) => {
const generateFile = new File([currentBlob], "filename.jpg", {
type: currentBlob.type,
});
myDropzone.addFile(generateFile);
});
On click of upload files just clear the files from dropzone.
All Files can be cleared using removeAllFiles() or specific file also you can delete by using removeFile(fileName).

Dropzone event handling not giving any life sign

i'm using dropzone to build an interface to an online storage api, for uploading files. I've to upload multiple files and to make an ajax call everytime a file is uploaded so that an input field of the hidden form below get added. It's not a big deal for itself, i just have to add a call to the init property of dropzone (i'm not creating a custo dropzone, i'm just using the default one). So at line 1581 i wrote:
Dropzone.options = {
init: function() {
this.on("addedfile", function(file) { alert("added file"); });
}
};
but when i add i file to the dropzone nothing happens.
I'm processing multiple files, so am I calling the wrong event? maybe should i call successmultiple? this is the dropzone tutorial. Any idea?
if you have a form, with an id="my-awesome-dropzone" like in the example
<form action="/file-upload"
class="dropzone"
id="my-awesome-dropzone"></form>
You have to create a config object in the same document, i.e. in the header
<script src="./path/to/dropzone.js"></script>
<script >
//"myAwesomeDropzone" is the camelized version of the HTML element's ID
Dropzone.options.myAwesomeDropzone = {
init: function() {
this.on("addedfile", function(file) { alert("Added file."); });
}
};
</script>
If instead of this, you are creating the dropzone by
var myDropzone = new Dropzone("form.myFormClass"); //or something like this
you have to add the options as the second parameter
var myDropzone = new Dropzone("form.myFormClass", {
init: function() {
this.on("addedfile", function(file) { alert("Added file."); });
}
});

Categories