Handler to grab variable values from another function - javascript

This is what I have so far
//file uploader
///////////////////////////
function uploader(){
var file = $(this).val()
var error = $(this).next('.req-error')
var fileLimit = $(this).attr('maxlength')-1
var uploadedFiles = $(this).siblings('.uploaded-file').length
//make uploaded file label
if(error.length ==1){
$(this).next().after('<div class="uploaded-file"><span>X</span>'+file+'</div>')
}else {
$(this).after('<div class="uploaded-file"><span>X</span>'+file+'</div>')
}
//count uploaded files
if(uploadedFiles >= fileLimit ){
$(this).attr('disabled', true)
}else{
$(this).removeAttr('disabled')
}
//clear input field
$(this).val('')
};
$(".input-file").change(uploader)
function removeFile(uploader){
$(this).remove()
}
$('.uploaded-file').live('click',removeFile)
I made a limit for how many files can be uploaded. Once the limit is reached, the input gets disable but, when a file is removed I want it to enable again if its under the limit. Im just not sure how to get the removeFile function to read the if statement from the uploader function.

It's probably best to have a counter that represents the number of files that have been uploaded. Place this in a var at the same level as both your uploader & removeFile functions:
var uploadedFiles = 0;
function uploader() {
...
}
function removeFile() {
...
}
Then increment/decrement this variable as you add/remove files.

Related

How to check if there is an image added to the dropzone?

I have this sample:
link
CODE HTML:
<div class="dropzone dz-clickable" id="myDrop">
<div class="dz-default dz-message" data-dz-message="">
<span>Upload or drag patient photo here</span>
</div>
</div>
CODE JS:
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#myDrop", {
addRemoveLinks: true,
url: "#",
maxFiles:1,
init: function() {
this.on("maxfilesexceeded", function(file) {
alert("You are not allowed to chose more than 1 file!");
this.removeFile(file);
});
}
});
var fileName = $('#profilePicture').val();
var mockFile = { name: fileName, size: 12345 };
myDropzone.options.addedfile.call(myDropzone, mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, "https://lh3.googleusercontent.com/-eubcS91wUNg/AAAAAAAAAAI/AAAAAAAAAL0/iE1Hduvbbqc/photo.jpg?sz=104");
What I want to do is to check if there is already a loaded image.
For example:
if(is an image loaded from the first?)
{
alert("you have already image, delete it first");
}else{
alert("you can upload image now");
}
Basically they do not want the user can put another picture if there is already loaded.
As you can see in my example, the first load an image ... if you want to load another one, allowed us (I do not want it).
Is there any way this can be restricted?
Thanks in advance!
DropZone provides the methods enable() and disable(), which you can use to control the usage of it.
You can use the drop or addedFile events to call this function:
init: function() {
this.on("addedFile", function(file) {
// do what you want with the added file
this.disable(); // disable the dropzone to prevent more files
});
}
Works for me , if the image is already uploaded in the dropzone , it does not allow me to add more .
this.on("addedfile", function (file) {
/*
Valid only in the dropzone . If a repetitive document shows ALERT and the previous item will disappear.(Sorry my English).
*/
if (this.files.length) {
var i, len, pre;
for (i = 0, len = this.files.length; i < len - 1; i++) {
if (this.files[i].name == file.name && this.files[i].size == file.size && this.files[i].lastModifiedDate.toString() == file.lastModifiedDate.toString()) {
alert("You have already image, delete it first")
return (pre = file.previewElement) != null ? pre.parentNode.removeChild(file.previewElement) : void 0;
}
}
}
});

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.

JavaScript check file extension for multiple uploads

I have contact form, and Js which validates the size of selected files. Also I want to add extension check. My code so far is
var inputs = $('input[type="file"]')
inputs.on('change', function () {
var size = 0;
inputs.each(function () {
$.each(this.files, function () {
size += this.size;
var names = [];
alert(x);
});
});
if (size > 19000000) {
alert('Ukupna dozvoljena veličina fajlova za upload je 20mb!');
$('.inputDugme').attr('disabled', 'disabled');
} else {
$('.inputDugme').removeAttr('disabled', 'disabled')
}
});
Is there I way to get extension of files, and save it in array. And then check content of array.
You can collect extension names like this:
var size = 0,
etx = [];
inputs.each(function () {
$.each(this.files, function () {
size += this.size;
ext.push(this.name.split('.').pop());
});
});
x[] = this.name; is not valid syntax in Javascript, you should use Array.prototype.push method.
try this.
var ext = filename.split('.')[filename.split('.').length - 1];

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.

Validation to restrict user form uploading heavy files

Hi I am using this code to restrict user from uploading the heavy files above 5mb. But this is only working for first file filed not for the rest of file fileds.
var n=1;
$(document).ready(function()
{
$('.add_field').click(function(){
if(n < 5)
{
n=n+1;
var newid="file"+n;
var input = $('#file1');
var clone = input.clone(true);
//clone.removeAttr ('id');
clone.attr('title','file'+n);
clone.attr('id','file'+n);
clone.val('');
clone.appendTo('.input_holder');}
});
$('.remove_field').click(function(){
if(n!=1)
{
n=n-1;
if($('.input_holder input:last-child').attr('id') != 'input_clone'){
$('.input_holder input:last-child').remove();
}
}
});
$("#file1").change(function ()
{
var iSize = ($("#file1")[0].files[0].size / 1024);
if(iSize>5000)
{
alert("Too Large FIle");
example_reset_html('file1d');
}
});
$("#file2").change(function ()
{
var iSize = ($("#file2")[0].files[0].size / 1024);
if(iSize>5000)
{
alert("Too Large FIle");
example_reset_html('file1d');
}
});
});
function example_reset_html(id) {
$('#'+id).html($('#'+id).html());
}
I checked this all browser and tried hacks but it seems that something is wrong and not working properly.
Can you bind your event on $('.input_holder')? It seems that element holds all file inputs so you only have to bind the change event to their parent.
$(".input_holder").change(function (e)
{
if(e.target.type==="file"){
var iSize = (e.target.files[0].size / 1024);
if(iSize>5000)
{
alert("Too Large FIle");
example_reset_html(e.target.id);
}
}
});

Categories

Resources