jQuery如何在不检查扩展名的情况下检查上传的文件是否是图像?
新手在这里。问题是我目前已经编写了一种方法来检查上传的文件大小和扩展名以便验证它。但是,检查扩展名不是解决方案,因为这种验证可能会导致很多问题。我想要做的是检查实际的文件类型并验证它而不使用扩展方法。我曾尝试使用 jQuery文件验证器,但无济于事......这是一个我当前代码中的代码段:
Newbie here. The problem is that I currently have written a method which checks uploaded file size and extension in order to validate it. However, checking extensions is not a solution as that kind of validation may cause a lot of problems. What I want to do is to check the actual file type and validate it without using extension method. I have tried to use jQuery file validator but to no avail... This is a snippet from my current code:
<input type='file' id='imageLoader' name='imageLoader' accept="image/*" data-type='image' />
脚本:
App.Dispatcher.on("uploadpic", function() {
$(":file").change(function() {
if (this.files && this.files[0] && this.files[0].name.match(/\.(jpg|jpeg|png|gif)$/) ) {
if(this.files[0].size>1048576) {
alert('File size is larger than 1MB!');
}
else {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
} else alert('This is not an image file!');
});
function imageIsLoaded(e) {
result = e.target.result;
$('#image').attr('src', result);
};
});
上传输入更改后调用它,验证后上传并显示图像。现在,我只关心验证,非常感谢任何帮助或想法!
It is called once the upload input changes and after validation it uploads and displays the image. For now, I only care about validation and any help or ideas would be greatly appreciated!
尝试这样的事情:
JavaScript
const file = this.files[0];
const fileType = file['type'];
const validImageTypes = ['image/gif', 'image/jpeg', 'image/png'];
if (!validImageTypes.includes(fileType)) {
// invalid file type code goes here.
}
jQuery
var file = this.files[0];
var fileType = file["type"];
var validImageTypes = ["image/gif", "image/jpeg", "image/png"];
if ($.inArray(fileType, validImageTypes) < 0) {
// invalid file type code goes here.
}