6

I am working on html and java script. I have file type input with that i want that the input file should only be .xls file

 <input type='file' id ="browse" name ="browse"/>

Now I want that the selected files only be .xls file ..and read that xls file. how to do that with java script...And if someone can explain me with the JavaScript code that will be more appreciated.

Dave Hogan
  • 3,201
  • 6
  • 29
  • 54
user2502227
  • 495
  • 1
  • 10
  • 23

3 Answers3

3

This will check the file extension after choosing a file. If it is not .xls, then it throws an alert error:

document.getElementById("browse").onchange = function() {
    var fileName = this.value;
    var fileExtension = fileName.substr(fileName.length - 4);

    console.log(fileExtension);
    if (fileExtension != ".xls") {
        alert("That ain't no .xls file!");
    }
}

Demo: http://jsfiddle.net/sn5sY/

tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 1
    This is a partial solution but can be easily bypassed and should be used in conjunction with server-side validation too. You cannot restrict this with client side-code alone. – Dave Hogan Jun 20 '13 at 14:40
1

Try with this code

<input type='file' id ="browse" name ="browse"/>

    var file = document.getElementById('browse');

    file.onchange = function(e){
        var ext = this.value.match(/\.([^\.]+)$/)[1];
        switch(ext)
        {
            case 'xls':
                alert('allowed');
                break;
            default:
                alert('not allowed');
                this.value='';
        }
};

And DEMO

Mirko Cianfarani
  • 2,023
  • 1
  • 23
  • 39
-1

It's not possible with standard HTML 4

Possible duplicate of Limit file format when using <input type="file">?

There is an accept attribute in HTML 5 but it's not guaranteed. More info can be found in the HTML 5 spec http://www.w3.org/html/wg/drafts/html/master/forms.html#attr-input-accept

Community
  • 1
  • 1
Dave Hogan
  • 3,201
  • 6
  • 29
  • 54