javascript 文件上传:检查图像是否有效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32222786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
file upload: check if valid image
提问by Moraru Alex
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?
有没有办法在javascript中找出所选文件是否是有效图像?
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.
我知道我可以检查文件扩展名。问题是有人可以将.txt
文件更改为.jpg
,它会通过验证。
回答by Kirby
Thank you Arūnas Smaliukas. Your answer got me close to what I wanted.
谢谢Arūnas Smaliukas。你的回答让我接近我想要的。
Image.onload
will only be called if the file is a valid image. So, it's not necessary to inspect this.width
in the onload()
call back.
Image.onload
仅当文件是有效图像时才会调用。因此,没有必要this.width
在onload()
回调中进行检查。
To detect that it is an invalid image, you can use Image.onerror
.
要检测它是无效图像,您可以使用Image.onerror
.
$().ready(function() {
$('[type="file"]').change(function() {
var fileInput = $(this);
if (fileInput.length && fileInput[0].files && fileInput[0].files.length) {
var url = window.URL || window.webkitURL;
var image = new Image();
image.onload = function() {
alert('Valid Image');
};
image.onerror = function() {
alert('Invalid image');
};
image.src = url.createObjectURL(fileInput[0].files[0]);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" />
回答by Arūnas Smaliukas
Firstly add accept="image/*"
on your input, to accept only image files
首先添加accept="image/*"
您的输入,仅接受图像文件
<input type="file" name="uploadPicture" accept="image/*" onChange="validateAndUpload(this);"/>
Second, you can create image object to see if it is true image
二、可以创建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);
}
};?