Dropzone Success function not working - javascript

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.

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);
};

How to pass DropZone JSON object to AngularJS?

In my Angular app, I'm using Dropzone with JQuery to upload files. I'm successfully able to upload file to my server and receive the response data. Now I need to pass that response data from JQuery to my AngularJS controller.
This is my dropzone code:
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(document).ready(function() {
// Smart Wizard
$('#wizard').smartWizard({labelFinish:'Upload'});
$('#file-dropzone').dropzone({
url: "UploadData/",
maxFilesize: 1024000,
paramName: "uploadfile",
acceptedFiles: ".csv",
maxFiles: 1,
dictDefaultMessage: "Drop CSV file here",
maxThumbnailFilesize: 5,
dictMaxFilesExceeded: "You can only uplaod one file",
init: function() {
this.on("sending", function(file, xhr, formData){
$(".busy-modal").show();
formData.append("format", $("#format").val());
});
this.on('success', function(file, json) {
$(".busy-modal").hide();
alert(JSON.stringify(json));
});
this.on('addedfile', function(file) {
});
}
});
});
function ResetDropZone()
{
Dropzone.forElement("#file-dropzone").removeAllFiles(true);
}
</script>
This is where I receive response data in JSON.
this.on('success', function(file, json) {
$(".busy-modal").hide();
alert(JSON.stringify(json));
});
I need to pass this json object to AngularJS controller. How can I do it?
So I got to do it by myself. Here's how:
I added a hidden text input with ng-model and ng-change attributes.
<input type="text" hidden id="fileResult" ng-model="fileResult" ng-change="fileResult_Changed()"/>
In my dropzone success function I changed value of that field and triggered input so that my ng-change event would fire.
this.on('success', function(file, json) {
$(".busy-modal").hide();
//alert(JSON.stringify(json));
$("#fileResult").val(JSON.stringify(json));
$("#fileResult").trigger('input');
});
And this is my ng-change event in my controller where I received data successfully
$scope.fileResult_Changed = function()
{
alert($scope.fileResult);
}
Ta-da!
Create dropzone directive
angular.module('myApp').directive('dropzone', ['$cookie', function ($cookie) {
return {
restrict: 'C',
scope: {
fileList: '=?'
},
link: function(scope, element, attrs) {
var config = {
url: '/upload',
maxFilesize: 16,
paramName: "file_content",
maxThumbnailFilesize: 10,
parallelUploads: 1,
autoProcessQueue: false,
headers: {
'X-CSRFToken': $cookies.get('csrftoken')
}
};
var eventHandlers = {
'addedfile': function(file) {
var dz = this;
scope.$apply(function () {
scope.file = file;
if (dz.files[1]!=null) {
dz.removeFile(dz.files[0]);
}
scope.fileAdded = true;
scope.processDropzone();
});
},
'success': function (file, response) {
// Do some thing on success
scope.$apply(function () {
scope.resetFile(file);
};
},
'error': function (file, reason) {
// Do something on error
}
};
scope.dropzone = new Dropzone(element[0], config);
angular.forEach(eventHandlers, function(handler, event) {
scope.dropzone.on(event, handler);
});
scope.processDropzone = function() {
scope.dropzone.processQueue();
};
scope.resetDropzone = function() {
scope.dropzone.removeAllFiles();
};
scope.resetFile = function(file) {
scope.dropzone.removeFile(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

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);
}
});

Categories