简单编写React文件上传组件

一、uploadFile.jsx

/** 
 * @Author: ltl
 * @Date: 2022-11-22 11:41:23
 * @LastEditTime: 2022-11-22 11:41:23
 * @LastEditors: ltl
 * @Description: 文件上传简单组件
 */
const React = require('react');
const { Component } = require('comps/libs');
const Input = require('comps/input/index');
import('./uploadFiles.css');

class UploadFile extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // 上传文件列表
            uploadFileList: [],
            // 显示上传文件列表
            fileListShow: [],
        };
    }

    componentDidMount() {
    }

    static getDerivedStateFromProps(props, state) {
        //判断是否有文件参数
        // if (props.uploadFileList && props.fileListShow) {
        //     return {
        //         uploadFileList: props.uploadFileList,
        //         fileListShow: props.fileListShow
        //     };
        // }
        if (  props.fileListShow) {
            return {
               
                fileListShow: props.fileListShow
            };
        }
        return null;
    }

    //选择文件方法
    selectFile = () => {
        var inputFile = document.querySelector('#inputFile');
        return inputFile.click();
    }

    //删除文件方法
    cancelFile = (index) => {
        let { uploadFileList, fileListShow } = this.state;
        //删除
        fileListShow.forEach((file, idx) => {
            if (index === idx) {
                uploadFileList = uploadFileList.filter((list, indx) => {
                    return file.fileName !== list.name
                })
            }
        })
        //删除
        let fileList = fileListShow.filter((list, idx) => {
            return idx !== index
        });
        this.setState({
            fileListShow: fileList,
            uploadFileList
        })
    }

    //上传文件 
    uploadFile = () => {
        let { uploadFileList, fileListShow } = this.state
        fileListShow = []
        let files = document.querySelector('#inputFile').files;
        var newUploadFileList = uploadFileList.concat(...files);
        //转化显示格式
        newUploadFileList.forEach(list => {
            let obj = {
                fileName: list.name,
                fileSize: list.size,
                fileType: list.type
            }
            fileListShow.push(obj);
        })
        this.setState({
            uploadFileList: newUploadFileList,
            fileListShow
        })
    };

    //请求上传文件 注:请在父组件调用该子组件方法
    /**
     * @description: 使用父掉子方法 本例用React.createRef()
     *  1、
     * constructor(props) {
     *  super(props);
     *  this.state = {}
     *  this.uploadFile = React.createRef();
     * }
     * 2、
     *  <UploadFile ref={this.uploadFile} />
     * 3、
     * 在父组件中调用该子组件onUploadHandler方法
     * this.uploadFile.current.onUploadHandler(参数);
     */
    onUploadHandler = (props) => {
        console.log(props);
        const { uploadFileList } = this.state;
        if (uploadFileList && uploadFileList.length !== 0) {
            const formData = new FormData($('#uploadForm')[0]);
            uploadFileList.forEach(file => {
                if (file.name.split(".")[1] == "zip" || file.name.split(".")[1] == "rar") {
                    noticers.info('请勿上传压缩文件');
                    return
                }
                formData.append('File', file)
            })
            $.ajax({
                url: `/bd/bbbbbb`, //后端接口
                type: 'POST',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                success: function (res) {
                    if (res.code == '0000') {
                        noticers.info("0000");
                    } else {
                        noticers.info("1111");
                    }
                },
                error: function (res) {
                    noticers.info("22222");
                },
                complete: function () {
                }
            })
        } else {
            noticers.info("请选择需要上传的文件!");
        }
    }

    render() {
        let { fileListShow } = this.state;
        return (
            <div className="upload-box">
                <div className="upload-name">附件:</div>
                <div>
                    <div>
                        <div style={{ display: 'block' }} className="upload-btn" onClick={this.selectFile}>选择文件</div>
                        <Input
                            style={{
                                display: 'none'
                            }}
                            type="file"
                            id="inputFile"
                            name="multipartFile"
                            multiple={true}
                            onChange={this.uploadFile}
                        />
                    </div>
                    <form
                        id="uploadForm"
                        action="Upload"
                        method="post"
                        enctype="multipart/form-data">
                        {
                            fileListShow.map((list, index) => {
                                return (
                                    <div className="file-list" key={index}>
                                        {
                                            list.id ?
                                                <a className="file-name" href={`/kkkk/download?gns=${list.filePath}`}>{list.fileName}</a> :
                                                <div className="file-name">{list.fileName}</div>
                                        }
                                        <div style={{ display: 'block' }} className="file-close" onClick={this.cancelFile.bind(this, index)}>X</div>
                                    </div>
                                )
                            })
                        }
                    </form>
                </div>
            </div>
        );
    }
}
module.exports = UploadFile;

二、uploadFile.css


.upload-box {
    margin-top: 20px;
    display: flex; 
    flex-flow: row;
}
.upload-box .upload-name {
    font-size: 12px;
}
.upload-box .upload-btn {
    border: 1px solid #999;
    cursor: pointer;
    font-size: 12px;
    width: 120px;
    height: 24px;
    line-height: 24px;
    text-align: center;
    border-radius: 6px;
}
.file-list {
    width: 380px;
    display: flex;
    justify-content: space-between;
}
.file-list .file-name {
    width: 180px;
    height: 30px;
    line-height: 30px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.file-list .file-close {
    cursor: pointer;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田思雨》

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值