Question

here i am trying to upload html/htm files on the click of a button. For that i am using 'input type=file' I have set the 'accept' attribute of it to accept only html/htm extensions like this:

<input type="file" name="htmla" id="htmla" accept="text/html" />

But it is showing different behaviour in different browsers

In firefox, it is accepting all files

In chrome, it is accepting html as well as images

In IE, the same as firefox

Is there a way to make it accept only html/htm files by any method like javascript or jquery?

Note: I am using this control in MVC 4

Was it helpful?

Solution 2

There is nothing in standard input control by which you can achieve it.

Yes there is an "accept" attribute on file input controls, where you can specify the types of files you want but this is not recognized by many browsers. So the best you can do is check the file name (extension) of file selected by user using Javascript or Jquery.

function ValidateFile() {
        var fileName = document.getElementById("inputFileId").value
        if (fileName == "") {
            alert("upload a valid File with .htm extension");
            return false;
        }
        else if (fileName.split(".")[1].toUpperCase() == "HTM")
            return true;
        else {
            alert("Invalid File");
            return false;
        }
        return true;
    }

But there's nothing preventing the user from renaming an executable to .html for example.

OTHER TIPS

This is HTML5 specific attribute. Not all browsers support it yet. For those that doesn't you will have to perform the check on the server. Another possibility is to check the extension of the file that was selected using javascript. Basically you could get the selected filename like this: $('#htmla').val(). And then regex for the extension.

<script>
  function test(obj,filter){

    var file = obj.value.match(/[^\/\\]+$/gi)[0];
    var rx = new RegExp('\\.(' + (filter?filter:'') + ')$','gi');
    if(filter&&file&&!file.match(rx)){
      alert("check the file type, only html is accepted");
      //input file
      //it's totally a bad idea...
      //document.body.innerHTML = "<input type='file' onchange=\"test(this,'html');\" >";

    }
  }
</script>
<body>
    <input id="inputFile" type="file" onchange="test(this,'html');">
</body>

maybe this should be for you swfupload

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top