【JS】JS格式化文件大小 單位:Bytes、KB、MB、GB


輸入一個表示文件大小的數字,自適應轉換到KB,MB,GB

  方法一:bytes自適應轉換到KB,MB,GB

 1 /// <summary>
 2 /// 格式化文件大小的JS方法
 3 /// </summary>
 4 /// <param name="filesize">文件的大小,傳入的是一個bytes為單位的參數</param>
 5 /// <returns>格式化后的值</returns>
 6 function renderSize(filesize){
 7     if(null==value||value==''){
 8         return "0 Bytes";
 9     }
10     var unitArr = new Array("Bytes","KB","MB","GB","TB","PB","EB","ZB","YB");
11     var index=0;
12     var srcsize = parseFloat(value);
13     index=Math.floor(Math.log(srcsize)/Math.log(1024));
14     var size =srcsize/Math.pow(1024,index);
15     size=size.toFixed(2);//保留的小數位數
16     return size+unitArr[index];
17 }

 

  方法二:bytes自適應轉換到KB,MB,GB

 1 function formatFileSize(fileSize) {
 2     if (fileSize < 1024) {
 3         return fileSize + 'B';
 4     } else if (fileSize < (1024*1024)) {
 5         var temp = fileSize / 1024;
 6         temp = temp.toFixed(2);
 7         return temp + 'KB';
 8     } else if (fileSize < (1024*1024*1024)) {
 9         var temp = fileSize / (1024*1024);
10         temp = temp.toFixed(2);
11         return temp + 'MB';
12     } else {
13         var temp = fileSize / (1024*1024*1024);
14         temp = temp.toFixed(2);
15         return temp + 'GB';
16     }
17 }

  方法三:可以設定輸入的文件長度的參數的原始單位,自適應轉換到KB,MB,GB

 1 /**
 2  * [fileLengthFormat 格式化文件大小]
 3  * @param  {[int]} total [文件大小]
 4  * @param  {[int]} n     [total參數的原始單位如果為Byte,則n設為1,如果為kb,則n設為2,如果為mb,則n設為3,以此類推]
 5  * @return {[string]}       [帶單位的文件大小的字符串]
 6  */
 7 function fileLengthFormat(total, n) {
 8     var format;
 9     var len = total / (1024.0);
10     if (len > 1000) {
11         return arguments.callee(len, ++n);
12     } else {
13         switch (n) {
14             case 1:
15                 format = len.toFixed(2) + "KB";
16                 break;
17             case 2:
18                 format = len.toFixed(2) + "MB";
19                 break;
20             case 3:
21                 format = len.toFixed(2) + "GB";
22                 break;
23             case 4:
24                 format = len.toFixed(2) + "TB";
25                 break;
26         }
27         return format;
28     }
29 }

 

1 //假如文件大小為1024byte,想自適應到kb,則如下傳參
2 fileLengthFormat(1024,1);//"1.00KB"
3 //假如文件大小為1024kb,想自適應到mb,則如下傳參
4 fileLengthFormat(1024,2);//"1.00MB"
5 //測試
6 fileLengthFormat(112233445566,1);//"104.53GB"

 

-------------------------------------------------------------------------------------------------------------


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM