如何允许<输入类型="文件">只接受图像文件?

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

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

如何实现这个功能?

888848 次浏览

使用输入标记的接受属性。要只接受PNG, JPEG和GIF,您可以使用以下代码:

<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>

或者仅仅是:

<label>Your Image File
<input type="file" name="myImage" accept="image/*" />
</label>

请注意,这只向浏览器提供了一个提示,提示要向用户显示什么文件类型,但这很容易避免,因此您也应该始终在服务器上验证上传的文件。

它应该可以在IE 10+, Chrome, Firefox, Safari 6+, Opera 15+上运行,但在手机上的支持非常粗略(截至2015年),根据一些报告,这实际上可能会阻止一些移动浏览器上传任何东西,所以一定要好好测试你的目标平台。

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

用这个:

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

工作在FF和Chrome。

像这样使用它

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

这对我很有效

https://jsfiddle.net/ermagrawal/5u4ftp3k/ < a href = " https://jsfiddle.net/ermagrawal/5u4ftp3k/ " > < / >

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

这可以通过

<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;
}
}

更多参考,请看这里

< p > # EYZ0 < br > # EYZ0 < / p >
< p >步骤:
1. 为输入标签
添加accept属性 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. 因此,您必须在服务器端编写文件内容验证。
使用type="file"和accept="image/*"(或者你想要的格式),允许用户选择特定格式的文件。但是你必须在客户端重新检查,因为用户可以选择其他类型的文件。

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

然后,在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
}
}
如果你想一次上传多张图片,你可以添加multiple属性输入。

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

简单而强大的方式(动态接受)

将格式放在数组中,如"image/*"

var upload=document.getElementById("upload");
var array=["video/mp4","image/png"];
upload.accept=array;
upload.addEventListener("change",()=>{


console.log(upload.value)
})
<input type="file" id="upload" >

你可以添加特定类型的图像或其他文件类型,并在你的代码中进行验证:

<input  style="margin-left: 10px; margin-top: 5px;" type="file" accept="image/x-png,image/jpeg,application/pdf"
(change)="handleFileInput($event,'creditRatingFile')" name="creditRatingFile" id="creditRatingFile">
    





  

handleFileInput(event) {
console.log(event);
const file = event.target.files[0];
if (file.size > 2097152) {
throw err;
} else if (
file.type !== "application/pdf"  &&
file.type !== "application/wps-office.pdf"   &&
file.type !== 'application/pdf'  && file.type !== 'image/jpg'  && file.type !== 'image/jpeg'  && file.type !== "image/png"
) {
throw err;
} else {
      

console.log('file valid')
}
}

在html中;

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

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

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

image_field = forms.ImageField(Here_are_the_parameters)

其他人的答案为ReactJS重构(hooks)

import React from 'react';


const ImageUploader = () => {


const handleImageUpload = (e) => {
// If no file selected, return
if (e.target.files.length === 0) return false;
const file = e.target.files[0];


// If no image selected, return
if (!/^image\//.test(file.type)) {
alert(`File ${file.name} is not an image.`);
return false;
}


// ...
};


return (
<>
<input type='file' accept='image/*' onChange={(e) => handleImageUpload(e)} />
</>
);
};


export default ImageUploader;


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

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

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