1 /// <summary>
2 /// 格式化文件大小的JS方法
3 /// </summary>
4 /// <param name="filesize">文件的大小,传入的是一个bytes为单位的参数</param>
5 /// <returns>格式化后的值</returns>
6 function renderSize(value){
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 }
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 }
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"