手写一个简单的React文件上传组件

话不多说先上代码
文件上传组件

import bindAll from 'lodash.bindall';
import React from 'react';
import {injectIntl} from 'react-intl';
import classNames from 'classnames';
import uploadIco from './upload-ico.svg'
import success from './success.svg'
import styles from "./file-upload.css";
import PropTypes from "prop-types";
import $axios from '../../request/index.js'
import uploadDefault from './upload-default.svg'

const imageType = ["apng","avif","bmp","gif","ico","cur","jpg","jpeg","jfif","pjpeg","pjp","png","svg","tif","tiff","webp"]

class FileUploadComponent extends React.Component {
    constructor (props) {
        super(props);
        bindAll(this, [
            'setFilteredDataRef',
            'selectFile'
        ]);
        this.state = {
            uploadSuccessFiles: [],
            stateIco:"",
            uploadImageShow: uploadDefault
        };
    }
    componentDidMount () {

    }
    componentDidUpdate (prevProps, prevState) {
        if (prevState.filterQuery !== this.state.filterQuery ||
            prevState.selectedTag !== this.state.selectedTag) {
            this.scrollToTop();
        }

    }

    scrollToTop () {
        this.filteredDataRef.scrollTop = 0;
    }
    setFilteredDataRef (ref) {
        this.filteredDataRef = ref;
    }

    render () {
        return (
            <div className={classNames(styles.rootDiv)}>
                {this.props.type==="file"?
                    <div className={classNames(styles.uploadFileViewBox)}>
                        <img className={classNames(styles.icoImage)} src={uploadIco}></img>
                        <button className={classNames(styles.uploadButton)} onClick={this.handleClick}>文件上传</button>
                    </div>:
                    <div className={classNames(styles.uploadImageViewBox)}>
                        <img src={this.state.uploadImageShow} className={classNames(styles.uploadImageButton)} onClick={this.handleClick}/>
                    </div>
                }
                <img src={this.state.stateIco}/>
                <p style={{display:this.props.type==="image"?"none":"",textAlign:"left"}} className={classNames(styles.fileName)}>{this.state.uploadSuccessFiles.join(",")}</p>
                <input type={"file"} multiple={this.props.multiple} style={{display:"none"}} onChangeCapture={this.selectFile} ref={input => this.inputElement = input}/>
            </div>
        );
    }

    selectFile(e){
        let that = this;
        if (that.props.model==="general"){
            Object.keys(e.target.files).forEach(k=> {
                let fileName = e.target.files[k].name;
                let fileType = fileName.substring(fileName.lastIndexOf(".")+1)
                if (imageType.indexOf(fileType)>=0 && that.props.type==="image") {
                    let formdata = new FormData();
                    formdata.append("file", e.target.files[k])
                    $axios.uploadFile("/front/file/upload", formdata).then((res) => {
                        if (res.data.code === 200) {
                            that.props.success(res.data)
                            that.setState({
                                uploadImageShow: res.data.result,
                            })
                        } else {
                            console.log("文件上传出错", res)
                        }
                    });
                } else {
                   console.log("只能上传图片类型")
                }
            });
        } else if (that.props.model==="sb3") {
            Object.keys(e.target.files).forEach(k => {
                let fileName = e.target.files[k].name;
                let formdata = new FormData();
                formdata.append("file", e.target.files[k]);
                $axios.uploadFile("/front/file/upload/source", formdata).then((res) => {
                    if (res.data.code === 200) {
                        that.props.success(res.data)
                        let temp = [];
                        temp = that.state.uploadSuccessFiles;
                        temp.push(fileName);
                        that.setState({
                            stateIco: success,
                            uploadSuccessFiles: temp
                        })
                    } else {
                        console.log("文件上传出错", res)
                    }
                });
            })
        }
    }

    handleClick = (e) => {
        this.inputElement.click();
    }
}

FileUploadComponent.propTypes = {
    multiple:PropTypes.bool,
    limit:PropTypes.number,
    type:PropTypes.string,
    success:PropTypes.func,
    model:PropTypes.string
};

FileUploadComponent.defaultProps = {
    multiple:true,
    limit:1,
    type:"file",// 文件file和图片image两种类型
    success:(res)=>{
        console.log(res)
    },
    model: "general"// 目前就general和sb3模式
};

export default injectIntl(FileUploadComponent);

@import "../../css/units.css";
@import "../../css/colors.css";

.rootDiv{
    width: 700px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.icoImage{
    vertical-align: middle;
}

.uploadButton{
    border-radius: 3px;
    border-width: 0px;
}

.uploadFileViewBox{
    background-color: rgb(77, 151, 255);
    width: auto;
    border-radius: 3px;
}

.uploadImageViewBox{
    width: auto;
    border-radius: 3px;
}

.fileName{
    width: auto;
    font-size: small;
    font-family: fangsong;
    color: #7b7b7b;

}

.uploadImageButton{
    max-width: 80px;
    min-width: 80px;
    border-radius: 3px;
    border-width: 1px;
    padding: 10px;
    border-style: dashed;
    border-color: #4d97ff;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值