项目踩坑,antd截取upload上传的图片file对象,存储在state中。

在项目中有项需求就是上传图片,但是跟后台约定的是上传file对象的同时post传值type和position的值,antd官方提供的案例是通过action:'接口链接’参数直接上传到接口中,所以我们需要截取一下file对象并存储到state中,在点击按钮的时候上传file、position和type的值。下面的详解:
1、首先在andt官网中复制好想要的上传组件案例;
2、 通过beforeUpload接收返回的file对象,官方是这样解释的:上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传( resolve 传入 File 或 Blob 对象则上传 resolve 传入对象)。注意:IE9 不支持该方法。 (file, fileList) => boolean | Promise;
3、通过setState的方法将file存放在state中;
4、用户删除图片的时候清空state ,通过onRemove函数在调用的时候删除state中file对象;
5、上传时先盘对json对象是否为空,使用的是JSON.stringify(file) === "{}"的方法;
以上是思路,下面附源码:
ps: 高阶大神有更好的方法可以留言小弟,代码有不整洁的地方勿喷,谢谢。

import React from "react";
import * as styles from './style.less';
import { Upload, message, Button, Icon} from 'antd';

//banner
export class ManageBanner extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            ...props,
            fileList: [{
                 uid: '-1',
                 name: 'xxx.png',
                 status: 'done',
                 url: 'http://www.baidu.com/xxx.png',
            }],
            file:{},
        }
    }

    componentWillReceiveProps(props){
        let {state} = this;
        if(state.fromId === props.fromId || state.positionId === props.positionId)
            return;
        this.setState({...props})
    }

    componentDidMount(){
        console.log('banner + type是 ----- ' + this.state.fromId);
        console.log('banner + position是 ----- ' + this.state.positionId);
    }

    handleChange = (info) => {
            let fileList = info.fileList;

            // 1. Limit the number of uploaded files
            // Only to show two recent uploaded files, and old ones will be replaced by the new
            fileList = fileList.slice(-2);

            // 2. Read from response and show file link
            fileList = fileList.map((file) => {
              if (file.response) {
                // Component will show file.url as link
                file.url = file.response.url;
              }
              return file;
            });

            // 3. Filter successfully uploaded files according to response from server
            fileList = fileList.filter((file) => {
              if (file.response) {
                return file.response.status === 'success';
              }
              return false;
            });

            this.setState({ fileList });
    }; //上传文件时的状态

    handleReturn =(file,fileList)=>{
        this.setState({file,fileList})
    }; //接收file对象

    handleRemove =()=>{
        this.setState({file:{}})
    }; //移除file对象

    handleUpLoadBtn = ()=>{
        let {file,fromId,positionId} = this.state;
        if(JSON.stringify(file) === "{}"){
            message.warning('未上传图片!')
        }else if(JSON.stringify(file) !== "{}"){
            console.log(file);
        }
    };  //点击确定提交file对象

    render(){
        const props = {
            beforeUpload:this.handleReturn,
            onChange: this.handleChange,
            onRemove: this.handleRemove,
            multiple: true,
        };
        return(
            <div className={styles.manage_banner}>
                 <Upload {...props}>
                     <p>上传图片:</p>
                     <Button>
                          <Icon type="upload" /> 上传图片
                     </Button>
                </Upload>
                <div onClick={::this.handleUpLoadBtn} className={styles.upload_btn}>
                    <Button type="primary">确定</Button>
                </div>
            </div>
        )
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40524880/article/details/85684668