• React后台管理手动封装图片上传组件


    分为两个文件夹,index.js(逻辑文件)    styled.js(样式文件)

    index.js文件,编写完成之后在对应的地方引入即可

    import React from "react"
    import { UploadContainer } from "./styled"
    import { Icon ,message} from "antd"
    import { fetch as fetchPro } from "whatwg-fetch"
    class Upload extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                imgUrl: ""
            }
            if (this.props.value) {
                this.state.imgUrl = this.props.value
            }
        }
        render() {
            let { imgUrl } = this.state
            return (
                <UploadContainer>
                    <input type="file" onChange={this.handleUpdate.bind(this)} ref="files" />
                    <div className="imgContent">
                        {imgUrl ? <img src={imgUrl} /> : <Icon type="plus" style={{ fontSize: 26 }} />}
                    </div>
                </UploadContainer>
            )
        }
        async handleUpdate() {
            let fileImg = this.refs.files.files[0];

            let formData = new FormData()

            formData.append("filesImg", fileImg)//第一个参数为后端规定字段,第二个参数时需要上传的图片

            let data = await fetchPro("/ajax/upload/files", {
                method: "post",
                body: formData
            }).then(res => res.json())//第一个参数为地址,第二个参数为配置项
            
            if(data.data.urlPath){
                this.setState({
                    imgUrl:data.data.urlPath
                })
            }else{
                message.error(data.data.info)
            }
        }
    }


    export default Upload

    styled.js文件

    import styled from "styled-components"
    
    export const UploadContainer = styled.div`
        110px;
        height:110px;
        border:1px dashed #ccc;
        position:relative;
        input{
            opacity:0;
            110px;
            height:100%;
            position:absolute;
            left:0;
            top:0;
            z-index:2;
        }
        .imgContent{
            padding:5px;
            100%;
            height:100%;
            position:absolute;
            left:0;
            top:0;
            display:flex;
            justify-content:center;
            align-items:center;
            img{
                100%;
                height:100%;
            }
        }
    `
  • 相关阅读:
    Vue 2.x windows环境下安装
    VSCODE官网下载缓慢或下载失败 解决办法
    angular cli 降级
    Win10 VS2019 设置 以管理员身份运行
    XSHELL 连接 阿里云ECS实例
    Chrome浏览器跨域设置
    DBeaver 执行 mysql 多条语句报错
    DBeaver 连接MySql 8.0 报错 Public Key Retrieval is not allowed
    DBeaver 连接MySql 8.0报错 Unable to load authentication plugin 'caching_sha2_password'
    Linux系统分区
  • 原文地址:https://www.cnblogs.com/Bree/p/12016167.html
Copyright © 2020-2023  润新知