Converting file size in bytes to human-readable string

后端 未结 19 2128
眼角桃花
眼角桃花 2020-11-28 17:58

I\'m using this function to convert a file size in bytes to a human-readable file size:

function getReadableFileSizeString(fileSizeInBytes) {
    var i = -1;         


        
19条回答
  •  情话喂你
    2020-11-28 18:20

    Solution as ReactJS Component

    Bytes = React.createClass({
        formatBytes() {
            var i = Math.floor(Math.log(this.props.bytes) / Math.log(1024));
            return !this.props.bytes && '0 Bytes' || (this.props.bytes / Math.pow(1024, i)).toFixed(2) + " " + ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][i]
        },
        render () {
            return (
                { this.formatBytes() }
            );
        }
    });
    

    UPDATE For those using es6 here is a stateless version of this same component

    const sufixes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    const getBytes = (bytes) => {
      const i = Math.floor(Math.log(bytes) / Math.log(1024));
      return !bytes && '0 Bytes' || (bytes / Math.pow(1024, i)).toFixed(2) + " " + sufixes[i];
    };
    
    const Bytes = ({ bytes }) => ({ getBytes(bytes) });
    
    Bytes.propTypes = {
      bytes: React.PropTypes.number,
    };
    

提交回复
热议问题