简体   繁体   English

如何使用JavaScript验证文件的大小?

[英]How do I validate the size of a file using JavaScript?

当单击页面上的上传按钮时...要检查在文件上传控件中选择的文件大小,并在文件大小超出限制时停止上传按钮的回发...使用jquery / javascript的方法是什么?

Although it's hardly a foolproof way, some browser check if you have a hidden input element specifying the maximum filesize like so: 尽管这不是万无一失的方法,但是某些浏览器会检查是否有隐藏的输入元素指定最大文件大小,如下所示:

<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />

[edit]It seems that this type of checking was never actually implemented by one of the main browsers. [edit]似乎这种检查实际上从未由一种主要的浏览器实施过。 It was merely hoped that they did. 只是希望他们做到了。

In that case you can only limit the file upload size (clientside) with flash, silverlight, java or some other clientside plugin. 在这种情况下,您只能使用Flash,Silverlight,Java或其他客户端插件来限制文件上传大小(客户端)。

You can't, you must use server-side PHP or ASP[.NET] to do so. 不能,您必须使用服务器端PHP或ASP [.NET]来这样做。 If it is possible, crackers will be stealing files. 如果有可能,黑客将窃取文件。

There is no way to implement this in a pure Javascript solution, since for security reasons, Javascript doesn't have access to your local filesystem. 由于安全原因,Javascript无法访问您的本地文件系统,因此无法在纯Javascript解决方案中实现此功能。 The only fool-proof way to do what you want is on the server. 做您想要的事情的唯一简单方法是在服务器上。 Depending on the technology you use, you may be able to intercept the request while it's still being sent and kill it based on the Content-length header. 根据您使用的技术,您可能能够在请求仍被发送时对其进行拦截,并根据Content-length标头将其终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM