javascript 以 mb 或 kb 为单位获取文件大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33531140/
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
Get file size in mb or kb
提问by Sergio Andrade
I want get the size of file in MB if the value is > 1024 or in KB if < 1024
如果值 > 1024,我想以 MB 为单位获取文件大小,如果 < 1024 以 KB 为单位
$(document).ready(function() {
$('input[type="file"]').change(function(event) {
var _size = this.files[0].size + 'mb';
alert(_size);
});
});
<input type="file">
回答by Akshaya Raghuvanshi
Please find the updated code below. See the working example here, Cheers!
请在下面找到更新的代码。请参阅此处的工作示例,干杯!
$(document).ready(function() {
$('input[type="file"]').change(function(event) {
var _size = this.files[0].size;
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB'),
i=0;while(_size>900){_size/=1024;i++;}
var exactSize = (Math.round(_size*100)/100)+' '+fSExt[i];
console.log('FILE SIZE = ',exactSize);
alert(exactSize);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" />
回答by Pete
Well the file size that .sizereturns is the bytes of 1024 would be 0.102MB. But anyways:
那么该文件大小.size的回报是1024字节会0.102MB。但无论如何:
$(document).ready(function() {
$('input[type="file"]').change(function(event) {
var totalBytes = this.files[0].size;
if(totalBytes < 1000000){
var _size = Math.floor(totalBytes/1000) + 'KB';
alert(_size);
}else{
var _size = Math.floor(totalBytes/1000000) + 'MB';
alert(_size);
}
});
});
Keep in mind what I wrote does not check for base cases, that mean if the file is under 1000 bytes then you will get 0KB (even if it's something like 435bytes). Also if your file is GB in size then it will just alert something like 2300MB instead. Also I get rid of the decimal so if you wanted something like 2.3MB then don't use Floor.
请记住,我写的内容不检查基本情况,这意味着如果文件小于 1000 字节,那么您将获得 0KB(即使它类似于 435 字节)。此外,如果您的文件大小为 GB,那么它只会发出类似 2300MB 的警报。我也去掉了小数点,所以如果你想要 2.3MB 之类的东西,那么不要使用 Floor。