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

送分小仙女□ 提交于 2019-12-07 07:51:17

问题


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


回答1:


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.




回答2:


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.




回答3:


<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



来源:https://stackoverflow.com/questions/15426674/how-to-force-input-type-file-to-accept-only-html-or-htm-files

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