function formatFileSize(bytes, decimalPlaces = 2) { if (bytes === 0) return '0 Bytes'; const k = 1024; // 1 KB = 1024 Bytes const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); // 计算单位索引 // 转换为目标单位并保留指定小数位数 return parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPlaces)) + ' ' + sizes[i]; }
bytes是以B为单位,也可以为其他单位,要注意以下几点:
sizes的元素基于bytes的单位
bytes的单位和sizes【0】一样