Reputation: 1835
I have a JS listener to check file type on file upload (input type file).
I placed it in the head of the document. It should work on load but it's not working.
<script type="text/javascript">
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
function checkFile(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "pdf" || sFileExtension === "doc" || sFileExtension === "docx" || sFileExtension === "png") || iFileSize > 10485760) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Size: " + iConvert + " MB \n\n";
txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
alert(txt);
}
}
}
</script>
My HTML
<input type="file" name="file" id="confirm">
I can make this work in the fiddle but not in my document - http://jsfiddle.net/4JHgk/
Upvotes: 0
Views: 210
Reputation: 2219
Make sure your script tag appears after your html declaration of the input and/or wrapt your function, like this:
window.onload=function(){
document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);
function checkFile(e) {
var file_list = e.target.files;
for (var i = 0, file; file = file_list[i]; i++) {
var sFileName = file.name;
var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = file.size;
var iConvert = (file.size / 10485760).toFixed(2);
if (!(sFileExtension === "pdf" || sFileExtension === "doc" || sFileExtension === "docx" || sFileExtension === "png") || iFileSize > 10485760) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Size: " + iConvert + " MB \n\n";
txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
alert(txt);
}
}
}
}
Upvotes: 1