Reputation: 150
I have a JQuery multi-file upload solution that requires restriction on file format and size.
Here's the JSFIDDLE, and the JS code follows below:
$(document).ready(function() {
if (window.File && window.FileList &&
window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\"><i class='fa fa-times'></i></span>" +
"</span>").insertAfter("#files");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
$(document).on('click', '[name=Reset]', function(){
$('.pip').remove();
})
The desired outcome is to allow me to set both the file type and size that can be easily changed.
Thanks for any help!
Upvotes: 0
Views: 611
Reputation: 89139
You can check the size
property of the file and the type
property of the file.
var maxSize = 20000;//maximum size for the file
var acceptedTypes = ["image/png", "image/jpg"];//accepted image types
if(f.size>maxSize){
//file is too big
}
if(acceptedTypes.indexOf(f.type)<0){
//file type is not accepted
}
JSFiddle: https://jsfiddle.net/ordmsw8p/
Upvotes: 1
Reputation: 789
You can set a condition right after you declare a value to your var f
if(f.size > 200000 || f.type !="image/png"){
alert("File too big or not a valid Type");
$("#files").val("");
}
You can also console.log(f); for more properties
Here is my version of your function:
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
if(f.size > 200000 || f.type !="image/png"){
alert("File too big or not a valid Type");
$("#files").val("");
}
else{
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\"><i class='fa fa-times'></i></span>" +
"</span>").insertAfter("#files");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
$(document).on('click', '[name=Reset]', function(){
$('.pip').remove();
})
Upvotes: 1