我正在读这个http://dev.w3.org/html5/markup/input.file.html,但我只找到了“接受”属性。
我试过这个
<input type="file" name="imagefilename" accept="image/x-png, image/gif, image/jpeg" />
是否可以对文件大小进行客户端验证?
我发现了IE的这种技术
<html>
<head>
<script>
function getSize()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>
是否有可能使用html5 filesystem api做同样的事情?
UPDATE
我能做到这一点(demo):
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type=file id=f max-size=32154 >
<input type=submit>
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].fileSize;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>
它工作正常,但我认为本地html5 attr更好用于验证
<form class="upload-form">
<input class="upload-file" data-max-size="2048" type="file" >
<input type=submit>
</form>
<script>
$(function(){
var fileInput = $('.upload-file');
var maxSize = fileInput.data('max-size');
$('.upload-form').submit(function(e){
if(fileInput.get(0).files.length){
var fileSize = fileInput.get(0).files[0].size; // in bytes
if(fileSize>maxSize){
alert('file size is more then' + maxSize + ' bytes');
return false;
}else{
alert('file size is correct- '+fileSize+' bytes');
}
}else{
alert('choose file, please');
return false;
}
});
});
</script>
我能做到这一点(demo):
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<form >
<input type="file" id="f" data-max-size="32154" />
<input type="submit" />
</form>
<script>
$(function(){
$('form').submit(function(){
var isOk = true;
$('input[type=file][data-max-size]').each(function(){
if(typeof this.files[0] !== 'undefined'){
var maxSize = parseInt($(this).attr('max-size'),10),
size = this.files[0].size;
isOk = maxSize > size;
return isOk;
}
});
return isOk;
});
});
</script>
</body>
</html>
如果您使用php作为后端,也许您可以使用此代码。
// Validate image file size
if (($_FILES["file-input"]["size"] > 2000000)) {
$msg = "Image File Size is Greater than 2MB.";
header("Location: ../product.php?error=$msg");
exit();
}