本文介绍了文件上传:检查有效的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< input type =filename =uploadPicture/ >
如果选择的文件是有效的图像,有什么办法可以在javascript中找到?
我知道我可以检查文件扩展名。问题是有人可以将 .txt
文件更改为 .jpg
,并通过验证。首先在你的输入中加入 accept =image / *
,只接受图像文件
< input type =filename =uploadPictureaccept =image / *onChange = validateAndUpload(本);/>
其次,您可以创建图像对象来查看它是否为真image
函数validateAndUpload(input){
var URL = window.URL || window.webkitURL;
var file = input.files [0];
if(file){
var image = new Image();
$ b $ image.onload = function(){
if(this.width){
console.log('Image has width,I think it real image');
// TODO:上传到后端
}
};
image.src = URL.createObjectURL(file);
}
};
I want to upload a file like this:
<input type="file" name="uploadPicture"/>
Is there any way to find out in javascript if the selected file is a valid image?
I know that I can check the file extension. The problem with that is someone can change a .txt
file to .jpg
and it would pass the validation.
解决方案
Firstly add accept="image/*"
on your input, to accept only image files
<input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>
Second, you can create image object to see if it is true image
function validateAndUpload(input){
var URL = window.URL || window.webkitURL;
var file = input.files[0];
if (file) {
var image = new Image();
image.onload = function() {
if (this.width) {
console.log('Image has width, I think it is real image');
//TODO: upload to backend
}
};
image.src = URL.createObjectURL(file);
}
};
这篇关于文件上传:检查有效的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!