图片压缩 base上传

import { IconButton, Avatar, Typography } from "@material-ui/core";
import _ServerURL from './../components/Ajax/_ServerURL';


import { ask } from "../components/_requst";

async function _upload_files(tag, base64Str, callback) {
    const url = `${_ServerURL.main}`+'upload/index';
    const body = {
        method: 'POST',
        body: {
            tag,
            value: base64Str,
        }
    };
    const res = await ask(url, body);
    let result = null;//
    if (res && 1 == res.code)
        result = res.value;//
    if (callback)
        callback(result);
}

function _press_image(file, thenFun, errFun, append = {}) {
    const { maxWidth = 600,
        maxHeight = 800,
        quality = 0.75,
        maxSize = 0.8,
        resize = true } = append;//
    let size = file.size / 1024 / 1024;
    new Promise((resolve, _) => {
        if (size > maxSize) { //压缩..
            const compress = new Compress();
            compress.compress([file], {
                size: maxSize, // the max size in MB, defaults to 2MB
                quality: quality, // the quality of the image, max is 1,
                maxWidth: maxWidth, // the max width of the output image, defaults to 1920px
                maxHeight: maxHeight, // the max height of the output image, defaults to 1920px
                resize: resize, // defaults to true, set false if you do not want to resize the image width and height
            }).then((res) => {
                resolve(res[0].prefix + res[0].data);
            });
        } else {//读取base64格式文件.
            const reader = new FileReader();
            reader.addEventListener('load', () => resolve(reader.result));
            reader.readAsDataURL(file);
        }
    }).then(res => thenFun(file, res)).catch(err => errFun(err));
}


/**
 * 显示图片,点击将会上传新的图片信息.
 * @param error 是否是错误
 * @param placeholder 说明文字
 * @param remark 追加说明
 * @param required 是否必填
 * @param value 当前的值.
 * @param onChange 更新处理方法 (url,keyword)
 * @param {number} tag 所属单位ID,此处如果不填写,则默认为9999.
 */
class JAvatar extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            loading: false,  /***是否在图片加载中...*/
            src:null,  /*** */
        }
    }

    static getDerivedStateFromProps(nextProps) {
        if (nextProps && null != nextProps && undefined != nextProps.onChange) {
            return {
                src:nextProps.value || null,
            }
        }
        return null;
    }



    fileChanges = (event) => {
        let source = event.target.files;
        this.setState({ loading: true });
        if (source.length > 0) {
            _press_image(source[0], (file, res) => {
                const tmp = {
                    ...file,
                    data: res   /***此处为base64格式的图片*/
                }
                // const { files } = this.state;//
                // files.push(tmp);
                // this.valueChange(files);
                // this.setState({ files, loading: false });
                this.wrapFiles(tmp);
            }, err => {
                this.setState({ loading: false });
            });
        } else {

        }
    }

    linkChange= ()=>{
        this.handler.click();
    }


    wrapFiles = (input) => {
        const {tag = 9999,onChange, size = 1, name} = this.props;
        _upload_files(tag, input.data, rest => {
            let url = rest.value;
            if (onChange) {
                onChange(url,name);
                this.setState({ loading: false });
            } else {
                this.setState({ src:url, loading: false });
            }
        });
    }

    render() {
        const { placeholder ,remark,error } = this.props;
        const {src} = this.state;
        return (<div style={{textAlign:'center'}}>
            <input ref={ref => this.handler = ref} onChange={this.fileChanges}
                accept="image/*" type="file" style={{ display: 'none' }} />
            <IconButton color={error ? 'secondary' : 'primary'} onClick={()=>{
                this.linkChange();
            }}>
                <Avatar src={src}
                    style={{ height: 120, width: 120 }}>
                    
                </Avatar>
            </IconButton>
            <Typography variant='body1'>
                <small>{placeholder}</small>
            </Typography>
            <Typography variant='body2'>
                <small style={{fontSize:8}}>{remark}</small>
            </Typography>
        </div>);
    }
}

export default JAvatar;

 

posted @ 2020-10-13 14:36  吃鸡小能手  阅读(105)  评论(0编辑  收藏  举报