Rella
Rella

Reputation: 66985

How to get type of user selected file with jQuery?

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?

Upvotes: 2

Views: 6530

Answers (4)

roselan
roselan

Reputation: 3775

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());
    }
});

Upvotes: 2

4b0
4b0

Reputation: 22321

Try this to get your file extension.

var fileName = "Ram.png";
alert(fileName.substring(fileName.lastIndexOf('.') + 1)); 

Upvotes: 2

Ankur
Ankur

Reputation: 12774

Just provide an id to you input and use this

document.getElementById(ID).files[0].type

Upvotes: 4

Marco Johannesen
Marco Johannesen

Reputation: 13134

$('input[type=file]').change(function(e){
  var file = $(this).val();
  var ext = file.split('.').pop();
  alert(ext);
});

Try this :)

Upvotes: 6

Related Questions