Display image and Validation of image extension before uploading file Using Javascript
file-upload, image, javascript, validation
Solution
I am able to solve it. Below ar the correct codes. :)
JavaScript
<SCRIPT type="text/javascript">
function ValidateFileUpload() {
var fuData = document.getElementById('fileChooser');
var FileUploadPath = fuData.value;
//To check if user upload any file
if (FileUploadPath == '') {
alert("Please upload an image");
} else {
var Extension = FileUploadPath.substring(
FileUploadPath.lastIndexOf('.') + 1).toLowerCase();
//The file uploaded is an image
if (Extension == "gif" || Extension == "png" || Extension == "bmp"
|| Extension == "jpeg" || Extension == "jpg") {
// To Display
if (fuData.files && fuData.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(fuData.files[0]);
}
}
//The file upload is NOT an image
else {
alert("Photo only allows file types of GIF, PNG, JPG, JPEG and BMP. ");
}
}
}
</SCRIPT>
The input on change:
<input type="file" name="dataFile" id="fileChooser" onchange="return ValidateFileUpload()" />
To display an image before uploaded:
<img src="images/noimg.jpg" id="blah">
Problem
My goal is to first validate the upload file is an image and if it is an image I will display it. I get the codes from Validation Code and Image Code. At first I was able to display image. However, when I combined display image code with validation code, I did not able to get both validation and display worked. Can anyone please help me? Below are my codes. Thanks in advance! :) ``` <input type="file" name="dataFile" id="fileChooser" onchange="readURL(this);" /> <SCRIPT type="text/javascript"> var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"]; function readURL(input) { var arrInputs = document.getElementById("fileChooser").value; 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; if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah').attr('src', e.target.result) }; reader.readAsDataURL(input.files[0]); } break; } } if (!blnValid) { alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", ")); return false; } } } } return true; } ```