react自定义多图片压缩上传

下载lrz压缩插件

npm install lrz

引用第三方组件

import React, { Component } from 'react';

import { message, Spin, Image } from 'antd';

import { upload, } from '../../common/aboutFile';

import { DeleteBasFilePost } from '../../pages/FaultReport/server'

import lrz from 'lrz';

import $ from 'jquery';

import styles from './index.module.scss';

import add from '../../assets/add.png';

定义变量

var file: any;

let imgArr: any[] = []

let CompressFileArr: any[] = []

let CompressArr: any[] = []

let fileArr: any[] = []

接收父组件内容

interface UploadImageProps {

    listId: any;

    ImgData: any;

    closeBtn: any;

    vallenght: any;

    addImagefun: Function;

    deleteImgfun: Function;

}

字段定义

interface UploadImageState {

    fileList_1: any[];

    fileListArr: any;

    previewImage: any;

    previewVisible: boolean;

    previewTitle: any;

    loading: boolean;

    operatesrcimgArr: any;

    uploading: boolean;

}

class UploadImage extends Component<UploadImageProps, UploadImageState> {

    constructor(props: UploadImageProps) {

        super(props);

        this.state = {

            fileList_1: [],

            fileListArr: [],

            previewImage: null,

            previewVisible: false,

            previewTitle: '',

            loading: false,

            operatesrcimgArr: [],

            uploading: false,

        }

    }

生命周期函数

    componentWillMount = () => { }

    componentWillReceiveProps(nextProps: any) {

        if (nextProps.ImgData.length > 0) {

            CompressFileArr = []

            for (let x = 0; x < nextProps.ImgData.length; x++) {

                CompressFileArr.push({ img: CONFIG.baseUrl + '/BasFile/GetUpdateFile?nID=' + nextProps.ImgData[x], id: nextProps.ImgData[x] })

            }

            this.setState({

                operatesrcimgArr: CompressFileArr

            })

        } else {

            CompressFileArr = []

            this.setState({

                operatesrcimgArr: CompressFileArr

            })

        }

    }

    compoenentWillUnmount() { }

    // 图片上传

    PicUploadFun = (val: any) => {

        CompressArr = []

        file = val.target.files;

        for (let x = 0; x < file.length; x++) {

            CompressArr.push({ fileid: x })

            this.setState({ uploading: true })

        }

        this.forceUpdate()

        for (let a = 0; a < file.length; a++) {

            if (!file[a]) {

                return;

            }

            // 匹配类型为image/开头的字符串

            // if (file[a].type === "image/png" || file[a].type === "image/jpeg" || file[a].type === "image/jpg") {

            //     // imgArr.push(URL.createObjectURL(file[a]))

            // } else {

            //     message.error("图片上传只支持JPG/PNG格式,请重新上传!");

            //     return;

            // }

            if (file[a].size / 1024 / 1024 > 1) {

                this.PictureCompressFun(file[a])

            } else {

                this.uploadImage(file[a])

            }

        }

    }

  封装的图片上传功能

    uploadImage = (fileObj: any) => {

        const formdata = new FormData() // 创建form对象

        formdata.append('avatar', fileObj)

        upload(formdata).then((res: any) => {

            if (res.status == 200) {

                CompressFileArr.push({ img: URL.createObjectURL(fileObj), id: res.data.Info })

                this.setState({

                    operatesrcimgArr: CompressFileArr.concat(fileArr),

                    uploading: false

                })

                $("#upload").val("");

                this.props.addImagefun(res.data.Info)

                this.forceUpdate()

            }

        })

    }

  图片压缩方法

    PictureCompressFun = (fileArr: any) => {

        this.setState({ uploading: true })

        if (fileArr.size / 1024 / 1024 > 1) {

            lrz(fileArr, { quality: 0.9 })

                .then((rst: any) => {

                    var arr = rst.base64.split(","),

                        mime = arr[0].match(/:(.*?);/)[1],

                        bstr = atob(arr[1]),

                        n = bstr.length,

                        u8arr = new Uint8Array(n);

                    while (n--) {

                        u8arr[n] = bstr.charCodeAt(n);

                    }

                    file = new File([u8arr], file.name, { type: mime })

                    this.uploadImage(file)

                })

        }

    }

删除图片

    CloseimgFun = (val: any) => {

        const { operatesrcimgArr } = this.state;

        const obj = { ID: val }

        DeleteBasFilePost(obj).then((res: any) => {

            CompressFileArr = operatesrcimgArr.filter((item: any, i: any) => item.id != val)

            this.setState({

                operatesrcimgArr: CompressFileArr

            })

            this.props.deleteImgfun(val)

            message.success('图片已删除')

        })

    }

    render() {

        const { operatesrcimgArr, uploading } = this.state;

        return (

            <div className='photo_upload'>

                <div className={styles.card}>

                    {operatesrcimgArr && operatesrcimgArr.map((respic: any, index: any) =>

                        <span className={styles.imgbox} key={index}>

                            <Image

                                style={{ marginRight: '10px' }}

                                className={styles.photo}

                                width={120}

                                src={respic.img}

                            />

                            <span className={styles.closeIcon} onClick={this.CloseimgFun.bind(this, respic.id)}>X</span>

                        </span>

                    )}

                    {uploading && CompressArr.map((loadingicon: any, i: any) =>

                        <span className={styles.loading_div} key={i + '上传中'}>

                            <Spin />

                            <span>上传中...</span>

                        </span>

                    )}

                    <label htmlFor='upload'>

                        <img src={add} className={styles.photo} />

                    </label>

                </div>

                <input

                    type='file'

                    accept='image/*'

                    id='upload'

                    multiple

                    className={styles.iptbtn}

                    onChange={this.PicUploadFun}

                />

            </div>

        );

    }

}

export default UploadImage;

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容