|
|
@@ -0,0 +1,98 @@
|
|
|
+
|
|
|
+/**
|
|
|
+ * 字节单位转换工具类
|
|
|
+ * 提供字节到KB、MB、GB等单位的转换方法
|
|
|
+ */
|
|
|
+
|
|
|
+export default class ByteConverter {
|
|
|
+ /**
|
|
|
+ * 将字节转换为KB,保留两位小数
|
|
|
+ * @param {number} bytes - 字节数
|
|
|
+ * @param {number} decimalPlaces - 小数位数,默认2位
|
|
|
+ * @returns {number} 转换后的KB数值
|
|
|
+ */
|
|
|
+ static bytesToKB(bytes, decimalPlaces = 2) {
|
|
|
+ if (typeof bytes !== 'number' || bytes < 0) {
|
|
|
+ console.warn('字节数必须为非负数');
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ const kb = bytes / 1024;
|
|
|
+ return Number(kb.toFixed(decimalPlaces));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 将字节转换为MB,保留两位小数
|
|
|
+ * @param {number} bytes - 字节数
|
|
|
+ * @param {number} decimalPlaces - 小数位数,默认2位
|
|
|
+ * @returns {number} 转换后的MB数值
|
|
|
+ */
|
|
|
+ static bytesToMB(bytes, decimalPlaces = 2) {
|
|
|
+ if (typeof bytes !== 'number' || bytes < 0) {
|
|
|
+ console.warn('字节数必须为非负数');
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ const mb = bytes / (1024 * 1024);
|
|
|
+ return Number(mb.toFixed(decimalPlaces));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 将字节转换为GB,保留两位小数
|
|
|
+ * @param {number} bytes - 字节数
|
|
|
+ * @param {number} decimalPlaces - 小数位数,默认2位
|
|
|
+ * @returns {number} 转换后的GB数值
|
|
|
+ */
|
|
|
+ static bytesToGB(bytes, decimalPlaces = 2) {
|
|
|
+ if (typeof bytes !== 'number' || bytes < 0) {
|
|
|
+ console.warn('字节数必须为非负数');
|
|
|
+ return 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ const gb = bytes / (1024 * 1024 * 1024);
|
|
|
+ return Number(gb.toFixed(decimalPlaces));
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 智能转换 - 根据字节大小自动选择最合适的单位
|
|
|
+ * @param {number} bytes - 字节数
|
|
|
+ * @param {number} decimalPlaces - 小数位数,默认2位
|
|
|
+ * @returns {object} 包含数值和单位的对象
|
|
|
+ */
|
|
|
+ static smartConvert(bytes, decimalPlaces = 2) {
|
|
|
+ if (typeof bytes !== 'number' || bytes < 0) {
|
|
|
+ console.warn('字节数必须为非负数');
|
|
|
+ return { value: 0, unit: 'B' };
|
|
|
+ }
|
|
|
+
|
|
|
+ if (bytes < 1024) {
|
|
|
+ return { value: bytes, unit: 'B' };
|
|
|
+ } else if (bytes < 1024 * 1024) {
|
|
|
+ return {
|
|
|
+ value: this.bytesToKB(bytes, decimalPlaces),
|
|
|
+ unit: 'KB'
|
|
|
+ };
|
|
|
+ } else if (bytes < 1024 * 1024 * 1024) {
|
|
|
+ return {
|
|
|
+ value: this.bytesToMB(bytes, decimalPlaces),
|
|
|
+ unit: 'MB'
|
|
|
+ };
|
|
|
+ } else {
|
|
|
+ return {
|
|
|
+ value: this.bytesToGB(bytes, decimalPlaces),
|
|
|
+ unit: 'GB'
|
|
|
+ };
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 格式化显示 - 返回带单位的字符串
|
|
|
+ * @param {number} bytes - 字节数
|
|
|
+ * @param {number} decimalPlaces - 小数位数,默认2位
|
|
|
+ * @returns {string} 格式化后的字符串
|
|
|
+ */
|
|
|
+ static formatBytes(bytes, decimalPlaces = 2) {
|
|
|
+ const result = this.smartConvert(bytes, decimalPlaces);
|
|
|
+ return `${result.value} ${result.unit}`;
|
|
|
+ }
|
|
|
+}
|