我只须要经过<input type="file">
标记上传图像文件。 javascript
如今,它接受全部文件类型。 可是,我想将其限制为仅包含.jpg
, .gif
等的特定图像文件扩展名。 php
如何实现此功能? html
使用这个: java
<input type="file" accept="image/*">
在FF和Chrome中都可使用。 浏览器
这样使用 服务器
<input type="file" accept=".png, .jpg, .jpeg" />
对我有用 编码
https://jsfiddle.net/ermagrawal/5u4ftp3k/ spa
您能够对<input type="file">
使用accept
属性,请阅读此文档http://www.w3schools.com/tags/att_input_accept.asp .net
这能够经过 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
脚步:
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>
说明: