我只需要通过<input type="file">标签上传图像文件。
现在,它接受所有的文件类型。但是,我想将其限制为特定的图像文件扩展名,包括.jpg, .gif等。
如何实现这个功能?
我只需要通过<input type="file">标签上传图像文件。
现在,它接受所有的文件类型。但是,我想将其限制为特定的图像文件扩展名,包括.jpg, .gif等。
如何实现这个功能?
当前回答
简单而强大的方式(动态接受)
将格式放在数组中,如"image/*"
var上传“上传”= document . getElementById (); var阵列= [/ mp4视频”,“image / p”); 上传. accept =阵列; 上传addEventListener(“change”()= > ' 上传游戏机。log (value)。 ') <输入类型=“文件”id=“上传”>
其他回答
其他人的答案为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=".png, .jpg, .jpeg" />
这对我很有效
https://jsfiddle.net/ermagrawal/5u4ftp3k/
用这个:
<input type="file" accept="image/*">
工作在FF和Chrome。
你可以添加特定类型的图像或其他文件类型,并在你的代码中进行验证:
<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')
}
}
简单而强大的方式(动态接受)
将格式放在数组中,如"image/*"
var上传“上传”= document . getElementById (); var阵列= [/ mp4视频”,“image / p”); 上传. accept =阵列; 上传addEventListener(“change”()= > ' 上传游戏机。log (value)。 ') <输入类型=“文件”id=“上传”>