HTML:如何将文件上传限制为仅图像?

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

HTML: How to limit file upload to be only images?

htmlimageuploadfile-upload

提问by JacobT

With HTML, how do I limit what kind of filetypes can be uploaded?

使用 HTML,如何限制可以上传的文件类型?

To easy the user experience, I want to limit file uploads to be only images (jpeg, gif, png).

为了简化用户体验,我想将文件上传限制为仅限图像(jpeg、gif、png)。

<form method="post" action="..." enctype="multipart/form-data">
<label for="image">Photo</label>
<input name="image" type="file" />
</form>

回答by Ms2ger

HTML5 says <input type="file" accept="image/*">. Of course, never trust client-side validation: Always check again on the server-side...

HTML5 说<input type="file" accept="image/*">。当然,永远不要相信客户端验证:总是在服务器端再次检查......

回答by Konga Raju

HTML5 File input has accept attribute and also multiple attribute. By using multiple attribute you can upload multiple images in an instance.

HTML5 文件输入具有接受属性和多属性。通过使用多个属性,您可以在一个实例中上传多个图像。

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

You can also limit multiple mime types.

您还可以限制多种 mime 类型。

<input type="file" multiple accept='image/*|audio/*|video/*' >

and another way of checking mime type using file object.

以及使用文件对象检查 mime 类型的另一种方法。

file object gives you name,size and type.

文件对象为您提供名称、大小和类型。

var files=e.target.files;

var mimeType=files[0].type; // You can get the mime type

You can also restrict the user for some file types to upload by the above code.

您还可以通过上述代码限制用户上传某些文件类型。

回答by Vineesh Puttanisseri

Here is the HTML for image upload. By default it will show image files only in the browsing window because we have put accept="image/*". But we can still change it from the dropdown and it will show all files. So the Javascript part validates whether or not the selected file is an actual image.

这是用于图像上传的 HTML。默认情况下,它只会在浏览窗口中显示图像文件,因为我们已经将accept="image/*". 但是我们仍然可以从下拉列表中更改它,它会显示所有文件。因此 Javascript 部分验证所选文件是否为实际图像。

 <div class="col-sm-8 img-upload-section">
     <input name="image3" type="file" accept="image/*" id="menu_images"/>
     <img id="menu_image" class="preview_img" />
     <input type="submit" value="Submit" />
 </div> 

Here on the change event we first check the size of the image. And in the second ifcondition we check whether or not it is an image file.

在 change 事件中,我们首先检查图像的大小。在第二个if条件下,我们检查它是否是一个图像文件。

this.files[0].type.indexOf("image")will be -1if it is not an image file.

this.files[0].type.indexOf("image")-1如果它不是图像文件,将会是。

document.getElementById("menu_images").onchange = function () {
    var reader = new FileReader();
    if(this.files[0].size>528385){
        alert("Image Size should not be greater than 500Kb");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();     
        return false;
    }
    if(this.files[0].type.indexOf("image")==-1){
        alert("Invalid Type");
        $("#menu_image").attr("src","blank");
        $("#menu_image").hide();  
        $('#menu_images').wrap('<form>').closest('form').get(0).reset();
        $('#menu_images').unwrap();         
        return false;
    }   
    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("menu_image").src = e.target.result;
        $("#menu_image").show(); 
    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);
};

回答by David

Edited

已编辑

If things were as they SHOULD be, you could do this via the "Accept" attribute.

如果事情本应如此,您可以通过“接受”属性执行此操作。

http://www.webmasterworld.com/forum21/6310.htm

http://www.webmasterworld.com/forum21/6310.htm

However, browsers pretty much ignore this, so this is irrelavant. The short answer is, i don't think there is a way to do it in HTML. You'd have to check it server-side instead.

然而,浏览器几乎忽略了这一点,所以这是无关紧要的。简短的回答是,我认为在 HTML 中没有办法做到这一点。您必须改为在服务器端检查它。

The following older post has some information that could help you with alternatives.

以下较旧的帖子提供了一些可以帮助您找到替代方案的信息。

File input 'accept' attribute - is it useful?

文件输入“接受”属性 - 有用吗?

回答by Robert K

You can only do this securely on the server-side. Using the "accept" attribute is good, but must also be validated on the server side lest users be able to cURL to your script without that limitation.

您只能在服务器端安全地执行此操作。使用“accept”属性很好,但还必须在服务器端进行验证,以免用户能够在没有该限制的情况下 cURL 到您的脚本。

I suggest that you: discard any non-image file, warn the user, and redisplay the form.

我建议您:丢弃任何非图像文件,警告用户,并重新显示表单。

回答by Arun Prabhakaran P

<script>

    function chng()
    {
        var typ=document.getElementById("fiile").value;
        var res = typ.match(".jp");

        if(res)
        {
            alert("sucess");
        }
        else
        {
            alert("Sorry only jpeg images are accepted");
            document.getElementById("fiile").value="; //clear the uploaded file
        }
    }

</script>

Now in the html part

现在在 html 部分

<input type="file" onchange="chng()">

this code will check if the uploaded file is a jpg file or not and restricts the upload of other types

此代码将检查上传的文件是否为 jpg 文件并限制其他类型的上传

回答by AndrewR

Checkout a project called Uploadify. http://www.uploadify.com/

签出一个名为 Uploadify 的项目。http://www.uploadify.com/

It's a Flash + jQuery based file uploader. This uses Flash's file selection dialog, which gives you the ability to filter file types, select multiple files at the same time, etc.

这是一个基于 Flash + jQuery 的文件上传器。这使用 Flash 的文件选择对话框,它使您能够过滤文件类型、同时选择多个文件等。

回答by John Lechowicz

Ultimately, the filter that is displayed in the Browse window is set by the browser. You can specify all of the filters you want in the Accept attribute, but you have no guarantee that your user's browser will adhere to it.

最终,浏览窗口中显示的过滤器由浏览器设置。您可以在 Accept 属性中指定所需的所有过滤器,但不能保证用户的浏览器会遵守它。

Your best bet is to do some kind of filtering in the back end on the server.

最好的办法是在服务器的后端进行某种过滤。