如何容许 只接受图像文件?

我只须要经过<input type="file">标记上传图像文件。 javascript

如今,它接受全部文件类型。 可是,我想将其限制为仅包含.jpg.gif等的特定图像文件扩展名。 php

如何实现此功能? html


#1楼

使用这个: java

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

在FF和Chrome中都可使用。 浏览器


#2楼

这样使用 服务器

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

对我有用 编码

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


#3楼

您能够对<input type="file">使用accept属性,请阅读此文档http://www.w3schools.com/tags/att_input_accept.asp .net


#4楼

这能够经过 code

<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


#5楼

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

对于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>

说明:

  1. accept属性过滤将在文件选择器弹出窗口中显示的文件。 可是,这不是验证。 这只是浏览器的提示。 用户仍然能够在弹出窗口中更改选项。
  2. javascript仅验证文件扩展名,而不能真正验证所选文件是实际的jpg仍是png。
  3. 所以,您必须在服务器端编写文件内容验证文件。
相关文章
相关标签/搜索