How validate max number of files before upload? - javascript

Hi I'm using the upload file plugin and I need to validate the number of files added before upload the file...Something like this
$('#fileupload').bind('fileuploadadd', function (e, data) {
filestoupload++;
var numOfDivs = $('.request').size();
if (numOfDivs < filestoupload) {
upload = false; // Is just an example.
}
});

This worked for me, on your fileupload definition add a beforesend, and there do the validation
var maxfiles=3;
$('#fileupload').fileupload(({
url: postFileUrl,
submit: function (event, files) {
//check for max files THIS IS WHERE YOU VALIDATE
//console.log(files.originalFiles.length);
var fileCount = files.originalFiles.length;
if (fileCount > maxFiles) {
alert("The max number of files is "+maxFiles);
throw 'This is not an error. This is just to abort javascript';
return false;
}
}
});
that throw is by far not elegant, if you happend to implement this and find a way to avoid that please make me know (for now is necesary or it will display the error alert for each file uploaded)

use data.files.length
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
var fileCount = data.files.length;
if (fileCount < filestoupload) {
upload = false;
}
});

Related

Why doesn't my .JSX script recognize every image in a folder which I want to mass-resize?

I have this JSX script I created but I feel like it's not checking for every file type in the filelist variable. Can someone take a look? It's very frustrating when I have it running and then for some reason a non-descript error message pops up and then it stops
Here is the script:
var inputFolder = Folder.selectDialog("Select a folder to process"),
fileList = inputFolder.getFiles(/\.(jpg|tif|psd|crw|cr2|nef|dcr|dc2|raw)$/i);
for(var i=0; i < fileList.length; i++) {
var doc = open(fileList[i]);
if(doc.width !== doc.height) {
if(doc.width > doc.height) {
doc.resizeCanvas(doc.width, doc.width)
} else {
doc.resizeCanvas(doc.height, doc.height)
}
}
if((doc.width && doc.height) > 1000) {
doc.resizeImage(1000, 1000);
} else {
doc.resizeImage(doc.width, doc.height);
}
doc.save();
doc.close();
}
This is the error message:
It seems that Folder.getFiles() doesn't accept RegExp objects, it only accepts a string or a function, beside that, it will also include Folder objects, you can change it to something like this to filter only files and only the file types you're interested in:
function filter(file) {
return (file instanceof File && /\.(jpg|tif|psd|crw|cr2|nef|dcr|dc2|raw)$/i.test(file.name))
}
fileList = inputFolder.getFiles(filter);

How to read the contents of files of a folder dragged and dropped in html5

There are many questions in stack overflow and the internet in general regarding this error, however, the context in which most of them are asked and answered does not match mine. I am making a gallery app with electron. The idea is for someone to drag a folder into a dropzone in the app, and the app opens the folder, iterates through each item in the folder, if it finds a folder, it just displays the name of the folder, if its an image, read the image and display it to the user. (Note, I have not explicitly checked the file type to be image. I am dragging a folder whose contents I am certain are either an image or a folder...I will add type checking later). Here is my code.
"use strict"
const filedrop = document.getElementById('drop-zone')
const importMyDrop = function (e) {
e.stopPropagation()
e.preventDefault()
const files = e.dataTransfer.items
if (files.length > 0) {
for (let i = 0; i < files.length; i++) {
let entry = e.dataTransfer.items[i].webkitGetAsEntry()
if (entry.isFile) {
console.log("file")
} else if (entry.isDirectory) {
onInitFs(entry)
}
}
}
}
const importDragOver = function (e) {
e.preventDefault()
e.dataTransfer.effectAllowed = 'copy'
e.dataTransfer.dropEffect = 'copy'
return false
}
function toArray(list) {
return Array.prototype.slice.call(list || [], 0)
}
function listResults(entries) {
let list = document.getElementById('list')
entries.forEach(function (entry) {
if (entry.isDirectory) {
list.innerHTML += `<li>${entry.name}</li>`
}
else if (entry.isFile) {
let reader = new FileReader()
reader.onloadend = function (e) {
list.innerHTML += "<p><strong>" + entry.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
}
reader.readAsDataURL(entry)//Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
}
})
}
function onInitFs(fs) {
let dirReader = fs.createReader()
let entries = []
// Call the reader.readEntries() until no more results are returned.
let readEntries = function () {
dirReader.readEntries(function (results) {
if (!results.length) {
listResults(entries.sort())
} else {
entries = entries.concat(toArray(results))
readEntries()
}
})
}
readEntries() // Start reading dirs.
}
filedrop.addEventListener('drop', importMyDrop)
filedrop.addEventListener('dragover', importDragOver)
The error is shown in the comment of the following line
reader.readAsDataURL(entry)//Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
I am following this post, and an example by sitepoint. Instructions in the first link go as far as iterating through each content of the folder, which I have successfully done. The second link shows how to display the image when it is drag and dropped. The only issue is that in my app, instead of dropping an image, the user will drop a folder and iterate through its contents.
How do I solve this error?

Validate function to check file extension from database

I need to validate the extension of an uploading file in js.I have successfully created a fuction like as follows.
function FileExtension_Validate(txt)
{
if( !txt.match(/\.(pdf)|(doc)|(PDF)|(DOC)|(docx)|(DOCX)$/)) { return false; } else {return true; }
}
But now my situation is, i have a database field which have data as follows
pdf,doc,PDF,DOC,docx,DOCX
Now i need to create a function based on the data from database.Is there any possible solution.Please help me..?
I solved it as follows..
function FileExtension_Validate(txt)
{
//alert(txt);
var extension=document.getElementById('extension').value;
var piece = extension.split(',');
var split=extension.split(',').length
var flag=0;
//alert(piece[0]);
for (var i = 0; i <split; i++)
{
var test=piece[i];
//alert(test);
if( txt!=test) { flag++;}
//else {return true; }
}
// alert(flag);
if(flag==split)
{
return false;
}
else{
return true;
}
in extension i have passed the extension of the uploade file

Plupload filters to allow all but a few extensions

Pupload lets you specify which file types can be uploaded, but I want to do the opposite: Allow all filetypes except a certain subset. Is this possible?
Someone posted a solution on Plupload's Github. You have to use the addFileFilter method.
plupload.addFileFilter('excluded_extensions', function(filter, file, cb){
var permitted = true;
var exts = filter[0].extensions.split(',');
//We have no excluded extensions, function presented default exclusion string, so allow anything
if(exts.length === 1 && exts[0] === "-")
permitted = true;
else
{
for(var i = 0; i < exts.length; i++)
{
var fileArray = file.name.split('.');
var extension = fileArray[fileArray.length - 1];
if(exts[i].toUpperCase() === extension.toUpperCase())
{
this.trigger('Error', {
code: plupload.FILE_EXTENSION_ERROR,
message: plupload.translate('File extension error.'),
file: file
});
permitted = false;
cb(false);
return;
}
}
}
if(permitted)
cb(true);
});
Source

Plupload retry if error

I'm trying to setup plupload so that if a file upload fails according to a certain error code, plupload will try to upload it again. Without success.
What I currently have
Here is my piece of code for now :
var attempts = 0; // number of attempts
function init(uploader) {
uploader.bind('Error', function(up, file) {
var code = JSON.parse(file.response).error.code;
console.log(code); //logs the error code
if(code === 503 && attempts > 3) {
up.stop();
file.status = plupload.FAILED;
file.retry = false;
// do stuff...
up.state = plupload.STARTED;
up.trigger("StateChanged");
attempts = 0;
}
else {
console.log("attempt : "+ attempts);
up.stop();
file.status = plupload.QUEUED;
attempts++;
file.retry = true;
up.state = plupload.STARTED;
up.trigger("StateChanged");
up.trigger("QueueChanged"); // ERROR HERE
}
})
}
Where I indicated the "ERROR HERE", my console shows me this :
TypeError: n.getSource is not a function
What am I doing wrong ?
Thanks a lot !
Why don't you add the file again on the queue?
http://www.plupload.com/docs/Uploader#addFile-filefileName-method
addFile(file, [fileName])

Categories