How to allow <input type="file"> to accept only image files?
Steps:
1. Add accept attribute to input tag
2. Validate with javascript
3. Add server side validation to verify if the content is really an expected file type
For HTML and javascript:
<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
function validateFileType(){
var fileName = document.getElementById("fileName").value;
var idxDot = fileName.lastIndexOf(".") + 1;
var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
//TO DO
}else{
alert("Only jpg/jpeg and png files are allowed!");
}
}
</script>
</body>
</html>
Explanation:
- The accept attribute filters the files that will be displayed in the file chooser popup. However, it is not a validation. It is only a hint to the browser. The user can still change the options in the popup.
- The javascript only validates for file extension, but cannot really verify if the select file is an actual jpg or png.
- So you have to write for file content validation on server side.
Using this:
<input type="file" accept="image/*">
works in both FF and Chrome.
Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:
<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>
Or simply:
<label>Your Image File
<input type="file" name="myImage" accept="image/*" />
</label>
Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.
It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports, this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.
For detailed browser support, see http://caniuse.com/#feat=input-file-accept
Use it like this
<input type="file" accept=".png, .jpg, .jpeg" />
It worked for me
https://jsfiddle.net/ermagrawal/5u4ftp3k/