Javascript 客户端使用 HTML5 检查文件大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4112575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Client Checking file size using HTML5?
提问by Khaled Musaied
I'm trying to ride the HTML5 wave but I'm facing a small issue. Before HTML5 we were checking the file size with flash but now the trend is to avoid using flash in web apps. Is there any way to check the file size in the client side using HTML5?
我正在尝试驾驭 HTML5 浪潮,但我面临一个小问题。在 HTML5 之前,我们使用 flash 检查文件大小,但现在的趋势是避免在 web 应用程序中使用 flash。有什么方法可以使用 HTML5 在客户端检查文件大小吗?
回答by Abdullah Jibaly
This works. Place it inside an event listener for when the input changes.
这有效。将其放置在事件侦听器中,以便在输入更改时使用。
if (typeof FileReader !== "undefined") {
var size = document.getElementById('myfile').files[0].size;
// check file size
}
回答by Ammadu
The accepted answer is actually correct, but you need to bind it to a event listener so that it would update when ever the file input is changed.
接受的答案实际上是正确的,但您需要将其绑定到事件侦听器,以便在文件输入更改时它会更新。
document.getElementById('fileInput').onchange = function(){
var filesize = document.getElementById('fileInput').files[0].size;
console.log(filesize);
}
If you are using jQuery library then the following code may come handy
如果您使用的是 jQuery 库,那么以下代码可能会派上用场
$('#fileInput').on('change',function(){
if($(this).get(0).files.length > 0){ // only if a file is selected
var fileSize = $(this).get(0).files[0].size;
console.log(fileSize);
}
});
Given that the conversion of the fileSize to display in which ever metric is up to you.
鉴于文件大小的转换以显示哪个指标取决于您。
回答by Konga Raju
HTML5 fie api supports to check the file size.
HTML5 fie api 支持检查文件大小。
read this article to get more info about file api
阅读本文以获取有关文件 api 的更多信息
http://www.html5rocks.com/en/tutorials/file/dndfiles/
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="fileInput" />
var size = document.getElementById("fileInput").files[0].size;
similarly file API gives name and type.
类似地,文件 API 给出了名称和类型。
回答by Alexander Leon
Personally, I would opt for this format:
就个人而言,我会选择这种格式:
$('#inputFile').bind('change', function(e) {
var data = e.originalEvent.target.files[0];
// and then ...
console.log(data.size + "is my file's size");
// or something more useful ...
if(data.size < 500000) {
// what your < 500kb file will do
}
}
回答by Julien
"no simple, cross-browser solution to achieve this" : Detecting file upload size on the client side?
“没有简单的跨浏览器解决方案来实现这一点”:在客户端检测文件上传大小?