how to force input type file to accept only .html or .htm files

旧街凉风 提交于 2019-12-05 17:12:40

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!