Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
5
rated 0 times [  12] [ 7]  / answers: 1 / hits: 122021  / 9 Years ago, wed, april 22, 2015, 12:00:00

Newbie here. The problem is that I currently have written a method which checks uploaded file size and extension in order to validate it. However, checking extensions is not a solution as that kind of validation may cause a lot of problems. What I want to do is to check the actual file type and validate it without using extension method. I have tried to use jQuery file validator but to no avail... This is a snippet from my current code:



<input type='file' id='imageLoader' name='imageLoader' accept=image/* data-type='image' />


Script:



App.Dispatcher.on(uploadpic, function() {         
$(:file).change(function() {
if (this.files && this.files[0] && this.files[0].name.match(/.(jpg|jpeg|png|gif)$/) ) {
if(this.files[0].size>1048576) {
alert('File size is larger than 1MB!');
}
else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
} else alert('This is not an image file!');
});
function imageIsLoaded(e) {
result = e.target.result;
$('#image').attr('src', result);
};
});


It is called once the upload input changes and after validation it uploads and displays the image. For now, I only care about validation and any help or ideas would be greatly appreciated!


More From » jquery

 Answers
38

Try something like this:



JavaScript



const file = this.files[0];
const fileType = file['type'];
const validImageTypes = ['image/gif', 'image/jpeg', 'image/png'];
if (!validImageTypes.includes(fileType)) {
// invalid file type code goes here.
}


jQuery



var file = this.files[0];
var fileType = file[type];
var validImageTypes = [image/gif, image/jpeg, image/png];
if ($.inArray(fileType, validImageTypes) < 0) {
// invalid file type code goes here.
}

[#66947] Tuesday, April 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
katharinek

Total Points: 302
Total Questions: 105
Total Answers: 123

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
katharinek questions
Sat, Jan 16, 21, 00:00, 3 Years ago
Sat, Dec 5, 20, 00:00, 4 Years ago
Mon, Nov 30, 20, 00:00, 4 Years ago
Fri, Aug 21, 20, 00:00, 4 Years ago
;