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

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

如何实现这个功能?


当前回答

如果你想一次上传多张图片,你可以添加多个属性输入。

上传多个文件:<input type="file" multiple accept='image/*'>

其他回答

只是作为一个补充:如果你想包括所有的现代图像文件类型与最好的跨浏览器支持,它应该是:

<input type="file" accept="image/apng, image/avif, image/gif, image/jpeg, image/png, image/svg+xml, image/webp">

这允许在大多数浏览器中显示的所有图像文件类型,同时排除不太常见的格式,如TIFF或不适合web的格式,如PSD。

这可以通过

<input type="file" accept="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;
    }
}

更多参考,请看这里

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

像这样使用它

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

这对我很有效

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

在html中;

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

这将接受所有的图像格式,但不接受其他文件,如pdf或视频。

但是如果你使用的是django, django forms.py;

image_field = forms.ImageField(Here_are_the_parameters)

你可以使用accept属性<input type="file">读取这个文档http://www.w3schools.com/tags/att_input_accept.asp