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


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

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

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

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

function formatFileSize(fileSize) {
    if (fileSize < 1024) {
        return fileSize + 'B';
    } else if (fileSize < (1024*1024)) {
        var temp = fileSize / 1024;
        temp = temp.toFixed(2);
        return temp + 'KB';
    } else if (fileSize < (1024*1024*1024)) {
        var temp = fileSize / (1024*1024);
        temp = temp.toFixed(2);
        return temp + 'MB';
    } else {
        var temp = fileSize / (1024*1024*1024);
        temp = temp.toFixed(2);
        return temp + 'GB';
    }
}

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

/**
 * [fileLengthFormat 格式化文件大小]
 * @param  {[int]} total [文件大小]
 * @param  {[int]} n     [total參數的原始單位如果為Byte,則n設為1,如果為kb,則n設為2,如果為mb,則n設為3,以此類推]
 * @return {[string]}       [帶單位的文件大小的字符串]
 */
function fileLengthFormat(total, n) {
    var format;
    var len = total / (1024.0);
    if (len > 1000) {
        return arguments.callee(len, ++n);
    } else {
        switch (n) {
            case 1:
                format = len.toFixed(2) + "KB";
                break;
            case 2:
                format = len.toFixed(2) + "MB";
                break;
            case 3:
                format = len.toFixed(2) + "GB";
                break;
            case 4:
                format = len.toFixed(2) + "TB";
                break;
        }
        return format;
    }
}
//假如文件大小為1024byte,想自適應到kb,則如下傳參
fileLengthFormat(1024,1);//"1.00KB"
//假如文件大小為1024kb,想自適應到mb,則如下傳參
fileLengthFormat(1024,2);//"1.00MB"
//測試
fileLengthFormat(112233445566,1);//"104.53GB"

 


免責聲明!

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



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