How to get type of file that user has selected (in some <input type="file" name="datafile">
) with jQuery and for example alert
it? At least its extention but some kind of grouped types like image
would be grate. Is there any jQuery plugin for that?
Asked
Active
Viewed 6,435 times
2

Rella
- 65,003
- 109
- 363
- 636
-
3http://stackoverflow.com/questions/4581308/jquery-or-javascript-get-mime-type-from-url i dont know, but this may be ur answer – Kris Oct 31 '11 at 12:12
4 Answers
6
$('input[type=file]').change(function(e){
var file = $(this).val();
var ext = file.split('.').pop();
alert(ext);
});
Try this :)

Marco Johannesen
- 13,084
- 6
- 31
- 36
4
Just provide an id to you input and use this
document.getElementById(ID).files[0].type

Ankur
- 12,676
- 7
- 37
- 67
-
This isn't supported in IE 9 and lower. It does work in the IE 10 previews, though. – Andy E Oct 31 '11 at 12:19
-
`.type` will return Content Type. Example: .xlsx file will return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", not "xlsx" – Van Tho Feb 04 '20 at 04:25
2
Try this to get your file extension.
var fileName = "Ram.png";
alert(fileName.substring(fileName.lastIndexOf('.') + 1));

Shawn Chin
- 84,080
- 19
- 162
- 191

4b0
- 21,981
- 30
- 95
- 142
2
why don't you use something like this:
$('input:file').change(function () {
var ext = this.value.split('.').pop();
console.log(ext);
});
if you want to use a "multiple" field, you can use something like this:
$('input:file').change(function () {
var $this = $(this);
if ( $this.prop('multiple') ) {
for ( var i=0; i<this.files.length; i++) {
var ext = this.files[i].fileName.split('.').pop();
// this.files[i].extension = ext; // usefull for future use
console.log(ext);
}
}
else {
console.log(this.value.split('.').pop());
}
});

roselan
- 3,755
- 1
- 20
- 20