利用antd上传组件customRequest API将文件上传到阿里OSS

chat

customRequest API可以覆盖上传组件的默认上传行为,使我们可以使用自定义上传方式。

customRequest api 文档:
https://github.com/react-component/upload#customrequest

alioss 文档:
https://help.aliyun.com/document_detail/64047.html?spm=a2c4g.11186623.6.1316.5d682c135GNBl4

业务需要将文件上传到阿里oss。
首先 初始化alisoss :

  componentDidMount() {
    this.aliOss = new OSS({
      accessKeyId: 'xxx',
      accessKeySecret: 'xxx',
      region: 'xxx',
      bucket: 'xxx',
    });
  }

onChange为文件状态改变的回调,上传中、完成、失败都会调用onChange。
使用customRequest api,使用组件上传时会执行handleUpload函数

  render() {
    const props = {
      onChange(info) {
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          message.success(`${info.file.name} 上传成功`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败.`);
        }
      },
    };
    return (
      <div>
        <Upload {...props} customRequest={this.handleUpload}>
          <Button>
            <Icon type="upload"/> Click to Upload
          </Button>
        </Upload>
      </div>
    );
  }

handleUpload 回调 会被传入一个对象,这里以options形参进行接收,
该对象包含以下属性:

onProgress: (event: { percent: number }): void
onError: (event: Error, body?: Object): void
onSuccess: (body: Object): void
data: Object
filename: String
file: File
withCredentials: Boolean
action: String
headers: Object

这里用到 file:传给oss 的file对象
onProgress :通知上传进度回调
onError:上传失败回调
onSuccess:上传成功回调

 handleUpload = async options => {
    console.log(options, 123);
    const { onSuccess, onError, file, onProgress } = options;
    if (this.aliOss) {
      try {
        await this.aliOss.multipartUpload(`test/${file.name}`, file, {
          progress: (progress, checkpoint) => {
            onProgress({ percent: progress * 100 }); // 执行onProgress 并传入当前进度,使得上传组件正确显示进度条
            this.changeUploadProgress(progress, checkpoint);// 这里是我用来更新state 上定义的进度,以控制显示 自己写的上传进度动画。
          },
        });
        onSuccess();
      } catch (e) {
        onError();
      }
    }
  };

版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/2306/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
利用antd上传组件customRequest API将文件上传到阿里OSS
antd design上传组件upload 使用 customRequest API将文件上传到阿里OSS
<<上一篇
下一篇>>
chat