如果选择的图像文件大于我设置的最大允许值,则我试图阻止它加载到画布上。逻辑检查图像并抛出警告,但仍然加载正在检查的图像。我怎样才能防止这种情况发生呢?此外,我需要能够清除以前加载的图像,如果一个新的加载和检查。新加载的图像太大,如果其太大,将不会检查其有效性或引发警告。
var fileInput = document.getElementById("file"),
renderButton = $("#renderButton"),
submit = $(".submit"),
imgly = new ImglyKit({
container: "#container",
ratio: 1 / 1
});
// As soon as the user selects a file...
fileInput.addEventListener("change", function (event) {
//CHECK FILE SIZE OF INPUT
if (window.File && window.FileReader && window.FileList && window.Blob)
{
//get the file size and file type from file input field
var fsize = $('#file')[0].files[0].size;
var ftype = $('#file')[0].files[0].type;
var fname = $('#file')[0].files[0].name;
if(fsize>54000) //do something if file size more than 1 mb (1048576)
{
$(".file-warning").html("<div class='alert alert-danger'><p>The image: <b>" + fname +"</b> is <b>" + fsize/1000 + "KB</b> and too big!</p></div>");
//alert("Type :"+ ftype +" | "+ fsize +" bites\n(File: "+fname+") Too big!");
}
}else{
alert("Please upgrade your browser, because your current browser lacks some new features we need!");
}
//END FILE SIZE CHECK
var file;
var fileToBlob = event.target.files[0];
var blob = new Blob([fileToBlob], {
"type": fileToBlob.type
});
// do stuff with blob
console.log(blob);
// Find the selected file
if (event.target.files) {
file = event.target.files[0];
} else {
file = event.target.value;
}
// Use FileReader to turn the selected
// file into a data url. ImglyKit needs
// a data url or an image
var reader = new FileReader();
reader.onload = (function (file) {
return function (e) {
data = e.target.result;
// Run ImglyKit with the selected file
try {
imgly.run(data);
} catch (e) {
if (e.name == "NoSupportError") {
alert("Your browser does not support canvas.");
} else if (e.name == "InvalidError") {
alert("The given file is not an image");
}
}
};
})(file);
reader.readAsDataURL(file);
});发布于 2015-04-14 17:09:40
当文件大小检查失败时-您应该保存错误的状态(通过更改为布尔变量),或者简单地中断函数的执行:
if(fsize>54000) //do something if file size more than 1 mb (1048576)
{
$(".file-warning").html("<div class='alert alert-danger'><p>The image: <b>" + fname +"</b> is <b>" + fsize/1000 + "KB</b> and too big!</p></div>");
//alert("Type :"+ ftype +" | "+ fsize +" bites\n(File: "+fname+") Too big!");
isValidSize=false; // this variable should be created somewhere at the top. It will keep the state of file-picker.
return; //this will stop any further actions;
}https://stackoverflow.com/questions/29633251
复制相似问题