Html <input type="file"> 按扩展名限制可选择的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5796537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 08:14:27  来源:igfitidea点击:

<input type="file"> limit selectable files by extensions

htmlinput-type-file

提问by haemse

How can someone limit the files that can be selected with the input type="file" element by extensions?

有人如何通过扩展名限制可以使用 input type="file" 元素选择的文件?

I already know the accept attribute, but in chrome it does limit the files by the last MIME Type defined (in this case "gif") and FF4 does not even limit anything.

我已经知道 accept 属性,但在 chrome 中它确实通过定义的最后一个 MIME 类型(在这种情况下为“gif”)来限制文件,而 FF4 甚至不限制任何内容。

<input type="file" accept="image/jpg, image/gif">

Am I doing anything wrong or is there another way?

我做错了什么还是有其他方法?

采纳答案by Sean Haddy

Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.

老实说,限制文件的最好方法是在服务器端。人们可以在客户端欺骗文件类型,因此在服务器传输时获取完整的文件名,解析文件类型,然后返回消息通常是最好的选择。

回答by Edi Budimilic

Easy way of doing it would be:

这样做的简单方法是:

<input type="file" accept=".gif,.jpg,.jpeg,.png,.doc,.docx">

Works with all browsers, except IE9. I haven't tested it in IE10+.

适用于所有浏览器,IE9 除外。我还没有在 IE10+ 中测试过。

回答by Joshua Carmody

NOTE: This answer is from 2011.It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answerand the docs.

注意:此答案来自 2011年。当时这是一个非常好的答案,但截至 2015 年,大多数浏览器都支持原生 HTML 属性,因此(通常)无需在 JS 中实现此类自定义逻辑。请参阅Edi 的回答文档



Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.

在上传文件之前,您可以使用Javascript检查文件的扩展名,如果不匹配,则阻止提交表单。要上传的文件的名称存储在表单元素的“值”字段中。

Here's a simple example that only allows files that end in ".gif" to be uploaded:

这是一个仅允许以“.gif”结尾的文件上传的简单示例:

<script type="text/javascript">
    function checkFile() {
        var fileElement = document.getElementById("uploadFile");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension.toLowerCase() == "gif") {
            return true;
        }
        else {
            alert("You must select a GIF file for upload");
            return false;
        }
    }
</script>

<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
    <input name="uploadFile" id="uploadFile" type="file" />

    <input type="submit" />
</form>

However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).

然而,这种方法并非万无一失。Sean Haddy 是正确的,您总是希望在服务器端进行检查,因为用户可以通过关闭 JavaScript 或在其到达浏览器后编辑您的代码来击败您的 Javascript 检查。除了客户端检查之外,一定要检查服务器端。此外,我还建议检查服务器端的大小,这样用户就不会因为 2 GB 的文件而使您的服务器崩溃(我不知道在不使用 Flash 或 Java 小程序或其他东西的情况下在客户端检查文件大小的方法) )。

However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.

但是,使用我在此处给出的方法事先检查客户端仍然很有用,因为它可以防止错误并且对不严重的恶作剧起到很小的威慑作用。

回答by prajwal

 function uploadFile() {
     var fileElement = document.getElementById("fileToUpload");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
         var fd = new FormData();
        fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEve`enter code here`ntListener("abort", uploadCanceled, false);
        xhr.open("POST", "/post_uploadReq");
        xhr.send(fd);
        }
        else {
            alert("You must select a valid odx,pdx,xml or cmo file for upload");
            return false;
        }

      }

tried this , works very well

试过了,效果很好