是否可以验证html5中input = file的大小和类型 [英] Is it possible to validate the size and type of input=file in html5

查看:129
本文介绍了是否可以验证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

推荐答案

我可以这样做(演示) :

<!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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆