如何强制输入类型文件仅接受.html或.htm文件 [英] how to force input type file to accept only .html or .htm files

查看:205
本文介绍了如何强制输入类型文件仅接受.html或.htm文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我试图通过单击按钮来上传html/htm文件.为此,我使用输入类型=文件",我将其接受"属性设置为仅接受这样的html/htm扩展名:

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

在firefox中,它接受所有文件

In firefox, it is accepting all files

在chrome中,它接受html和图像

In chrome, it is accepting html as well as images

在IE中,与firefox相同

In IE, the same as firefox

是否可以通过javascript或jquery之类的方法使其仅接受html/htm文件?

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

注意:我正在MVC 4中使用此控件

推荐答案

在标准输入控件中,没有什么可以实现的.

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

是的,文件输入控件上有一个"accept"属性,您可以在其中指定所需的文件类型,但是许多浏览器无法识别.因此,您最好的办法就是检查用户使用Javascript或Jquery选择的文件的文件名(扩展名).

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

但是没有什么可以阻止用户将可执行文件重命名为.html.

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

这篇关于如何强制输入类型文件仅接受.html或.htm文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆