[英]How to check type of uploaded image through FileReader?
There is the following code which makes preview before uploading on the server:有以下代码可以在上传到服务器之前进行预览:
$(function(){
var preview = $(".preview");
$("#menu_image").change(function(event){
var input = $(event.currentTarget);
var file = input[0].files[0];
var reader = new FileReader();
reader.onload = function(e){
var img = new Image;
img.onload = function() {
if ((img.with != 160) || (img.height != 160)) {
return;
}
preview.attr("src", img.src);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
});
But this code doesn't check file's type.但是此代码不检查文件的类型。 How can I do it?我该怎么做? Thanks in advance.提前致谢。
You don't need to load the FileReader to know file type.您无需加载 FileReader 即可了解文件类型。 Using your code:使用您的代码:
var file = input[0].files[0];
is as easy as checking the file.type
property.就像检查file.type
属性一样简单。
You can check if the file is an image:您可以检查文件是否为图像:
if (file.type.match('image.*')) {
console.log("is an image");
}
And which type of image is:以及哪种类型的图像是:
if (file.type.match('image.*')) {
console.log("is an image");
console.log("Show type of image: ", file.type.split("/")[1]);
}
Note that file.type.split("/")[1]
should be an "image"注意file.type.split("/")[1]
应该是一个“图像”
You can do something similar to check the file extension:您可以执行类似的操作来检查文件扩展名:
var extension = file.name.substring(file.name.lastIndexOf('.'));
// Only process image files.
var validFileType = ".jpg , .png , .bmp";
if (validFileType.toLowerCase().indexOf(extension) < 0) {
alert("please select valid file type. The supported file types are .jpg , .png , .bmp");
return false;
}
Try using the extension selector like this:尝试使用这样的扩展选择器:
if($('img[src $= "jpg"]')) // if extension is jpg then dosomething
dosomething;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.