如何在客户端使用HTML和Javascript验证文件大小 [英] how validate file size using HTML and Javascript on client side

查看:59
本文介绍了如何在客户端使用HTML和Javascript验证文件大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用JavaScript在客户端验证文件大小?我使用 type = file 来选择文件

解决方案

更新2013
截至此编辑,所有主流浏览器都支持File API,并且在版本10中支持IE

http://caniuse.com/#search=file%20api



如果您仍然需要支持IE9及以下版本,您仍然可能希望使用SWFUpload,尽管此时它应该更像是一个后备,因为html5文件api在SWFUpload不能达到。 html5文件api基于firefox的文件api,如下所述。



另请参阅此重复问题
客户端使用HTML5检查文件大小?
$ b

更新: Firefox已将其API更改为此 https://developer.mozilla.org/zh/ DOM / FileReader



您可以像firefox一样执行此操作。



html:


 < form action =method =getaccept-charset =utf-8> ; 
< input type =filename =filevalue =id =file>
< p>< input type =submitvalue =Continue& rarr;>< / p>
< / form>


javascript:

  var filesize = document.forms [0] .file.files [0] .fileSize 

如果在IE中有办法做到这一点,我不知道它。它可能涉及到activeX或其他一些垃圾。



编辑:
我发现这个此处,如何在IE中执行此操作

 < 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(大小+字节);
}
< / script>
< / head>
< body>
<表格名称=上传>
< input type =filename =file>
< input type =buttonvalue =Size?的onClick = 的getSize(); >
< / form>
< / body>
< / html>


How can I validate the file size on the client side using JavaScript? I am using type=file for selecting the file

解决方案

UPDATE 2013 as of this edit, the File API is supported in all major browsers, and in IE as of version 10

http://caniuse.com/#search=file%20api

You may still wish to use SWFUpload if you still need to support IE9 and under, though at this point it should probably be more of a fallback, since the html5 file api has support on mobile platforms where SWFUpload cannot reach. The html5 file api is based on firefox's file api as noted below.

See also this duplicate question Client Checking file size using HTML5?

UPDATE: Firefox has changed their API to this https://developer.mozilla.org/en/DOM/FileReader

You can do it in firefox like so

html:

<form action="" method="get" accept-charset="utf-8">
<input type="file" name="file" value="" id="file">
<p><input type="submit" value="Continue &rarr;"></p>
</form>

javascript:

var filesize = document.forms[0].file.files[0].fileSize

if there's a way to do this in IE, I don't know it. It probably involves activeX or some other such rubbish.

edit: I found this here, HOW TO DO THIS IN IE

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

这篇关于如何在客户端使用HTML和Javascript验证文件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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