Ramda 将 file.size 转指定单位的值

125 阅读1分钟

文件大小以字节为单位

The size read-only property of the Blob interface returns the size of the Blob or File in bytes.

Blob.size

存储容量换算

存储容量换算

思路

要做的就是算除法,

转单位为 KB 的值,需要 file.size / 1024

转单位为 MB 的值,需要 file.size / Math.pow(1024, 2)

依此类推,核心代码是这一行:

R.divide(size, Math.pow(1024, exponent))

接下来就要求出 file.size 转期望单位的值要除以 1024 的次数

exponent

  1. 定义单位数组

    const units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  2. 求出期望单位的下标再 +1

    R.pipe( R.indexOf(R.__, units), R.inc )('MB'); // 2
    

    转单位为 MB 的值,需要 file.size / Math.pow(1024, 2)

最终代码

import * as R from 'ramda';
import { units } from '@/const/index.js';

const calcExponent = R.pipe( R.indexOf(R.__, units), R.inc );

const fileSizeOf = R.curry(
  (unit, size) => R.divide( size, Math.pow(1024, calcExponent(unit)) )
);

fileSizeOf('KB', Math.pow(1024, 1)); // 1

const fileSizeOfMB = fileSizeOf('MB');
fileSizeOfMB( Math.pow(1024, 2) ); // 1

比如用 a-upload 上传文件,before-upload 内判断若文件大于 500MB,则显示错误信息

function beforeUpload(file) {
  const isSizeValid = R.compose( R.lte(R.__, 500), fileSizeOf('MB') );
  if ( !isSizeValid(file.size) ) {
    message.error('文件最大限 500MB');
    return;
  }
  /* ... */
}