在项目中有项需求就是上传图片,但是跟后台约定的是上传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 { U