Html 如何允许 <input type="file"> 只接受图像文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3828554/
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 04:43:08  来源:igfitidea点击:

How to allow <input type="file"> to accept only image files?

html

提问by kbvishnu

I need to upload only image file through <input type="file">tag.

我只需要通过<input type="file">标签上传图像文件。

Right now, it accepts all file types. But, I want to restrict it to only specific image file extensions which include .jpg, .gifetc.

现在,它接受所有文件类型。但是,我想将它限制为仅特定的图像文件的扩展名,其中包括.jpg.gif等等。

How can I achieve this functionality?

我怎样才能实现这个功能?

回答by madcap laughs

Use the acceptattribute of the input tag. So to accept only PNGs, JPEGs and GIFs you can use the following code:

使用输入标签的accept属性。因此,要仅接受 PNG、JPEG 和 GIF,您可以使用以下代码:

<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />

Or simply:

或者干脆:

<input type="file" name="myImage" accept="image/*" />

Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.

请注意,这仅向浏览器提供了关于向用户显示哪些文件类型的提示,但这很容易被规避,因此您也应该始终验证服务器上上传的文件。

It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.

它应该可以在 IE 10+、Chrome、Firefox、Safari 6+、Opera 15+ 中运行,但对移动设备的支持非常粗略(截至 2015 年),并且根据一些报告,这实际上可能会阻止某些移动浏览器上传任何内容,因此一定要好好测试你的目标平台。

For detailed browser support, see http://caniuse.com/#feat=input-file-accept

有关详细的浏览器支持,请参阅http://caniuse.com/#feat=input-file-accept

回答by Tyilo

Using this:

使用这个:

<input type="file" accept="image/*">

works in both FF and Chrome.

适用于 FF 和 Chrome。

回答by Er. Mohit Agrawal

Use it like this

像这样使用它

<input type="file" accept=".png, .jpg, .jpeg" />

It worked for me

它对我有用

https://jsfiddle.net/ermagrawal/5u4ftp3k/

https://jsfiddle.net/ermagrawal/5u4ftp3k/

回答by Surya Kameswara Rao Ravi

Steps:
1. Add accept attribute to input tag
2. Validate with javascript
3. Add server side validation to verify if the content is really an expected file type

步骤:
1. 将接受属性添加到输入标签
2. 使用 javascript 验证
3. 添加服务器端验证以验证内容是否真的是预期的文件类型

For HTML and javascript:

对于 HTML 和 JavaScript:

<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
    function validateFileType(){
        var fileName = document.getElementById("fileName").value;
        var idxDot = fileName.lastIndexOf(".") + 1;
        var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
        if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
            //TO DO
        }else{
            alert("Only jpg/jpeg and png files are allowed!");
        }   
    }
</script>
</body>
</html>

Explanation:

解释:

  1. The accept attribute filters the files that will be displayed in the file chooser popup. However, it is not a validation. It is only a hint to the browser. The user can still change the options in the popup.
  2. The javascript only validates for file extension, but cannot really verify if the select file is an actual jpg or png.
  3. So you have to write for file content validation on server side.
  1. accept 属性过滤将显示在文件选择器弹出窗口中的文件。但是,这不是验证。这只是对浏览器的提示。用户仍然可以更改弹出窗口中的选项。
  2. javascript 仅验证文件扩展名,但无法真正验证选择的文件是实际的 jpg 还是 png。
  3. 所以你必须在服务器端编写文件内容验证。

回答by Ashok Devatwal

This can be achieved by

这可以通过

<input type="file" accept="image/*" /> 

But this is not a good way. you have to code on the server side to check the file an image or not.

但这不是一个好方法。您必须在服务器端编码以检查文件是否为图像。

Check if image file is an actual image or fake image

检查图像文件是真实图像还是假图像

if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    }
    else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

For more reference, see here

如需更多参考,请参见此处

http://www.w3schools.com/tags/att_input_accept.asp
http://www.w3schools.com/php/php_file_upload.asp

http://www.w3schools.com/tags/att_input_accept.asp
http://www.w3schools.com/php/php_file_upload.asp

回答by yussan

you can use acceptattribute for <input type="file">read this docs http://www.w3schools.com/tags/att_input_accept.asp

您可以使用accept属性来<input type="file">阅读此文档http://www.w3schools.com/tags/att_input_accept.asp

回答by Mati Cassanelli

Using type="file" and accept="image/*" (or the format you want), allow the user to chose a file with specific format. But you have to re check it again in client side, because the user can select other type of files. This works for me.

使用 type="file" 和 accept="image/*"(或您想要的格式),允许用户选择具有特定格式的文件。但是你必须在客户端重新检查它,因为用户可以选择其他类型的文件。这对我有用。

<input #imageInput accept="image/*" (change)="processFile(imageInput)" name="upload-photo" type="file" id="upload-photo" />

And then, in your javascript script

然后,在你的 javascript 脚本中

processFile(imageInput) {
    if (imageInput.files[0]) {
      const file: File = imageInput.files[0];
      var pattern = /image-*/;

      if (!file.type.match(pattern)) {
        alert('Invalid format');
        return;
      }

      // here you can do whatever you want with your image. Now you are sure that it is an image
    }
  }

回答by JerryGoyal

If you want to upload multiple images at once you can add multipleattribute to input.

如果你想一次上传多张图片,你可以multiple在 input 中添加属性。

upload multiple files: <input type="file" multiple accept='image/*'>