Dropzone js upload validation with multiple files - javascript

I am currently working on with Dropzonejs for uploading files. For each file I am attaching a form field. I have to do something like this, if the form field attached with that file is not empty, I want to upload. Else, I show error message below the thumbnail. I have pretty much accomplished this.
The only problem I am facing is, suppose there are 3 files selected. 1st one doesn't have the form field attached but 2nd and 3rd have form field attached. The error message is shown saying the form field is required. But the rest of the files, 2nd and 3rd are not uploaded. It only uploads when I provide the required field on the 1st one.
So, my question is how do I upload only those that have form field attached but leave the rest in the Dropzone area for the user to fill the form field?
Update:
Once the files are added, the user is required to put the values in the form field. If the form field is not filled, error message is shown and the file is not uploaded but remain in the queue. Else, if the field is filled, the file is uploaded.

You might hook into an event.
There is the accept function:
is a function that gets a file and a done function as parameter. If the done function is invoked without a parameter, the file will be processed. If you pass an error message it will be displayed and the file will not be uploaded. This function will not be called if the file is too big or doesn't match the mime types.
dz.options = {
accept: function(file, done) {
if (valid) {
done();
}
else {
done("error message");
}
}
}
Unfortunately, this seems to be called automatically and immediately after a drop.
You might find the other events more appropriate for your app e.g. send: function(file, xhr, formData).

Related

How to get Dropzone.js in combination with multiple input and select fields working

Im trying to get dropzone.js working with multiple input and select fields working.
Also reading the dropzone.js documentation i saw that the dropzone form looks like a stand alone form. So when i tried to add more input and select fields inside the dropzone form, the complete form gets covered by a dropzone, and i wanted just one part to be a dropzone. Also i found i way fixing it reading other stackoverflow articles.
What i did is i created a form with 3 input fields, 7 select options and + 1 dropzone, and i have 1 submit button which should submit it all together.
I have followed this stackoverflow article: Integrating Dropzone.js into existing HTML form with other fields
Problem: When I submit the form the file starts uploading (Progress animation shows it) but the file gets not uploaded to the server, and the form gets not completly submited, also the fields values are not sent to the database.
This is the form start code:
<form id="drform" name="formapdf2" method="post" action="dodaj-save.php" autocomplete="off" enctype="multipart/form-data">
This is the submit button code:
<button id="sbmtbutton" class="btn btn-primary" name="insert" type="submit">Registruj radnika</button>
Here is the JS code i use:
Dropzone.options.dropfile = {
acceptedFiles: 'image/*',
maxFiles: 1,
resizeWidth: 300,
resizeHeight: 300,
resizeMethod: 'contain',
resizeQuality: 1.0,
maxFilesize: 4,
autoProcessQueue: false,
url: 'dodaj-save.php',
addRemoveLinks: true,
init: function() {
dzClosure = this; // Makes sure that 'this' is understood inside the functions below.
// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("sbmtbutton").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
//send all the form data along with the files:
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("name", jQuery("#dzfname").val());
formData.append("qrcode", jQuery("#dzfqrcode").val());
formData.append("company", jQuery("#select_id").val());
formData.append("money", jQuery("#dzfmoney").val());
formData.append("checkin", jQuery("#dzfcheckin").val());
formData.append("checkout", jQuery("#dzfcheckout").val());
formData.append("checkin1", jQuery("#dzfcheckin1").val());
formData.append("checkout1", jQuery("#dzfcheckout1").val());
formData.append("checkin2", jQuery("#dzfcheckin2").val());
formData.append("checkout2", jQuery("#dzfcheckout2").val());
});
}
}
I have the PHP code for upload too, but im not sure if the php code is the problem, and should i show this code too here. If you need anything else to identify what is the problem please let me know. And I hope i didnt break any stackoverflow rule since this is my first post.
Try this. It's a little different from how you are doing it, but it works really well.
First thing you can do is to stop Dropzone.js from auto detecting the the form tags by adding this outside of your $(document).ready(function(){}):
Dropzone.autoDiscover = false;
Then create the Dropzone instance with the AJAX function. Do this inside of the $(document).ready(function(){}), but outside of the button click event:
let myDropzone = new Dropzone('.dropzone', { //Give your input (or form if you're not sending anything else) a class of dropzone
autoProcessQueue: false,
acceptedFiles: ".svg", // Add accepted file types here
url: "dodaj-save.php", // Your PHP file here
init: function() {
this.on("addedfile", function() {
//Do something before the file gets processed.
})
this.on("sending", function(file, xhr, formData){
//Do something when the file gets processed.
//This is a good time to append additional information to the formData. It's where I add tags to make the image searchable.
formData.append('tags', 'cat-cats-kittens-meow')
}),
this.on("success", function(file, xhr) {
//Do something after the file has been successfully processed e.g. remove classes and make things go back to normal.
}),
this.on("complete", function() {
//Do something after the file has been both successfully or unsuccessfully processed.
//This is where I remove all attached files from the input, otherwise they get processed again next time if you havent refreshed the page.
myDropzone.removeAllFiles();
}),
this.on("error", function(file, errorMessage, xhr) {
//Do something if there is an error.
//This is where I like to alert to the user what the error was and reload the page after.
alert(errorMessage);
window.location.reload();
})
}
});
Then loop through all the attached files and process all of them consecutively when the submit button is clicked:
const uploadBtn = document.querySelector('#sbmtbutton');
uploadBtn.addEventListener('click', () => {
const acceptedFiles = myDropzone.getAcceptedFiles();
for (let i = 0; i < acceptedFiles.length; i++) {
myDropzone.processFile(acceptedFiles[i])
}
})
That is all from the Javascript side. In your PHP file you can process the files and move it to a folder on the server:
<?php
$folder_name = 'path-to-your-folder/';
if (!empty($_FILES)) {
$temp_file = $_FILES['file']['tmp_name'];
$filename = $_POST['tags'].'.svg'; //Grabbing those tags that I appended to formData in the AJAX request and renaming the file based on those tags. Be sure to add your image extension
$location = $folder_name.$filename;
move_uploaded_file($temp_file, $location);
}
?>
I hope this helps! =) It's also important to note that you would have to run this on a local server if you want the PHP to run when you are testing this on your local machine. You can set up a local server by following these instructions.
You can use PHP and JS to bring the images back from the server and display it on the client side, but that might be beyond the scope of this question. If you want me to add it, just mention it in a comment an I'll add it as an update to the answer.

how do i add validation to this method in angular controller?

Hi I have a controller where the post method still takes place even when an error comes up to say the fields weren't completed. You refresh the page and entry goes from the view.
$scope.create = function () {
var account = Account.save($scope.account);
modalService.success('Success! Your Account has been created!');
$uibModalInstance.close(account);
};
I have tried a few things, but they haven't worked. I need the method to return false if the form hasn't been filled in or fields are missing. Basically a 422 error; as the post goes to an api endpoint.
The example above is my code and need to add some validation into it, but just don't know where to start.
Really tired and need some help quickly.
Thank you in advance.
You could wait till that save method actually complete an ajax and then respond to you
var account = Account.save($scope.account).$promise.then(function(){
//success function
modalService.success('Success! Your Account has been created!');
$uibModalInstance.close(account);
}, function(error){ //error function
//here is the place you can do error handling part.
console.log('Error occured, do handle it here.')
});
Update
If you wanted to make sure before submitting form user should be enter a all form fields and all. Then you could take use of angular form validation feature. Where you can disabled form submit button till all form required fields are filled up & have required attribute over the fields which are required.

Synchronous Requests Depreciated [duplicate]

I have a very complex form which contains multiple tabs. Each tab contains a unique Plupload instance (for uploading multiple images). The form allows a user to upload a medical image 'case' where each case is made up of multiple imaging 'studies' (e.g. CT scans) and each study contains multiple images.
When the user clicks the 'submit' button, I intercept the click with jQuery because I need to do the following:
Check the required fields are entered [easy]
Get a unique id number from my server. This id number is required by each Plupload instance to know which directory to upload to.
In my function called upon form submission I have the following code snippet:
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
});
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
return false;
}
With my current logic, I need the script to pause UNTIL it gets case_id. This was possible before jQuery 1.8 but the $.ajax() async : false property has been deprecated.
My question is two-fold:
Is there a way to hold up the script until I get the required case_id?
If not, any idea how I could change my logic to work around this?
You might be wondering why case_id is so important. The plupload instances do their upload before the form submits and they need a directory to upload to. I want the images being uploaded to go into a folder on my server called case_id. This will let the PHP script on the server figure out what to do with them once it gets the rest of the form POSTed data.
This is a very common 'problem' that can be solved pretty easily by using callbacks appropriately.
$("#submitButton").click(function (event) {
event.preventDefault(); //Don't submit the form, we'll submit it manually.
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
alert("something went wrong");
} else {
$("#referenceToTheForm").submit();
}
});
});
Long story short, keeping the "deal with problems or submit the form" inside of the callback to the $.get call will essentially cause the script to 'pause' until it gets the data back. Then you can use something like spin.js to give the user a good waiting experience until it's done.

I need help finding an alternative to synchronous jQuery ajax

I have a very complex form which contains multiple tabs. Each tab contains a unique Plupload instance (for uploading multiple images). The form allows a user to upload a medical image 'case' where each case is made up of multiple imaging 'studies' (e.g. CT scans) and each study contains multiple images.
When the user clicks the 'submit' button, I intercept the click with jQuery because I need to do the following:
Check the required fields are entered [easy]
Get a unique id number from my server. This id number is required by each Plupload instance to know which directory to upload to.
In my function called upon form submission I have the following code snippet:
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
});
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
return false;
}
With my current logic, I need the script to pause UNTIL it gets case_id. This was possible before jQuery 1.8 but the $.ajax() async : false property has been deprecated.
My question is two-fold:
Is there a way to hold up the script until I get the required case_id?
If not, any idea how I could change my logic to work around this?
You might be wondering why case_id is so important. The plupload instances do their upload before the form submits and they need a directory to upload to. I want the images being uploaded to go into a folder on my server called case_id. This will let the PHP script on the server figure out what to do with them once it gets the rest of the form POSTed data.
This is a very common 'problem' that can be solved pretty easily by using callbacks appropriately.
$("#submitButton").click(function (event) {
event.preventDefault(); //Don't submit the form, we'll submit it manually.
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
alert("something went wrong");
} else {
$("#referenceToTheForm").submit();
}
});
});
Long story short, keeping the "deal with problems or submit the form" inside of the callback to the $.get call will essentially cause the script to 'pause' until it gets the data back. Then you can use something like spin.js to give the user a good waiting experience until it's done.

No-Flash multiple images uploader script with options for every upload

I need a no-flash images uploader script that supports:
Multiple Uploads
Drag & Drop
Progress bar for every upload
Small preview for every upload
Resumable downloads
Selectable preferences for every upload
So something like this script: jQuery-File-Upload
A screenshot:
But I need to add some options for every upload, for example: "Title" and "Category", than I need to run a function for every upload that takes the submitted datas e puts them into my database, is there any way I can do it?
If you use the templates that come with jQuery-File-Upload, you can add in your own fields that appear when each item is added to the queue. The plugin will need to know about these fields, so you can use the callback to add more data:
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
// get content from the new input fields
var inputs = data.context.find('select'); // or whatever inputs you added
// assign values to data.formData
// you can simply $.extend() the new inputs with $(this), and $.serializeArray() both
data.formData = $.extend(inputs.serializeArray(), $(this).serializeArray());
});
See this for more information.

Categories