是否可以在 html5 中验证 input=file 的大小和类型 [英] Is it possible to validate the size and type of input=file in html5
本文介绍了是否可以在 html5 中验证 input=file 的大小和类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读这个http://dev.w3.org/html5/markup/input.file.html,但我只找到了accept"属性.
I was reading this http://dev.w3.org/html5/markup/input.file.html, but I only found the "accept" attribute.
我试过了
<input type="file" name="imagefilename" accept="image/x-png, image/gif, image/jpeg" />
是否可以在客户端验证文件大小?
Is it possible client-side validation of file size?
我为 IE 找到了这种技术
I found this technique for 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 文件系统 api 来做同样的事情?
Is it possible to do the same using html5 filesystem api ?
更新
我可以这样做(演示):
<!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 来验证
It is working fine, but I think It will be better to a native html5 attr to validate
推荐答案
我可以做到 (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>
这篇关于是否可以在 html5 中验证 input=file 的大小和类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文