Reputation: 95
I need help with file size on upload. i'd like to add file maximum size 2MB.
I use javascript code and i'm not good with javascript so if you guys can add file size into my code. Thanks.
var _validFileExtensions = [".jpg", ".jpeg", ".png"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
Upvotes: 1
Views: 1115
Reputation: 796
It can still be optimized in various ways, so its open for any performance, semantic or refactoring edits. I am not an expert.
var _maxFilsize
you have to write size of max file size to be allowed in bytes. Function Validate
has parameter oForm
which expects an HTML object
, through which it can search for input fields. input
elements in an array, arrInputs
.arrInputs[i].type
in string
form in variable inputType
inputType
with different input types in if/else
statements.returns
a function
that validates the matched input fieldvalidateImage
takes an argument which is simply the input field's property that contains list of files selected by user, arrInputs[i].files
.validateImage
Function there is a for loop that iterates over the list of files and validates their type
and size
, and returns true
or false
depending upon validity of file.var _maxFilesize = 2000000;// in bytes
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
var inputType;
var i = 0;
var arrLength = arrInputs.length;
for (i; i < arrLength; i++) {
inputType =arrInputs[i].type.toString();
if (inputType === "file"){
return validateImage(arrInputs[i].files);//calls function for validating image
}else if(inputType === "email"){
//call email validating function
}//add validation for more fields
}
}
function validateImage(file){
var j = 0;
var NumberOfFiles = file.length;
for(j; j< NumberOfFiles;j++){
if ((file[j].type === "image/jpeg" || file[j].type === "image/png")&& (file[j].size)<= _maxFilesize){
return true //or whatever you want to do here like calling a function to upadate view, or something
}
else{
return false //or whatever you want to do here like calling a function to upadate view, or something
}
}
}
Upvotes: 2