react 前端批量直传阿里云oss

213 阅读1分钟
  • 在上传前,需要先在阿里云上设置相关参数,具体操作可以按照阿里云官方文档指定的步骤进行:
  • 链接:www.alibabacloud.com/help/zh/oss…
  • 效果:

企业微信截图_e6679953-e808-4720-b89c-c9d7e309ed7c.png

1//引入必要的文件
import OSS from 'ali-oss';
import md5 from 'blueimp-md5';
2//定义上传组件
<FormItem label="资料文件" {...formItemLayoutItem}>
  {getFieldDecorator('uploadDoc', {
    initialValue: [],
    rules: [{ required: true, message: '请上传文件' }]
   })(
  <Upload
    ref={this.uploadEl}
    listType='text'
    fileList={fileList}
    multiple={true}
    onChange={this.handleFileChange}
    beforeUpload={this.beforeUpload}
    transformFile={this.transformFile}
    customRequest={this.customRequest}
  >
  <Button onClick={this.handleUploadClick}>
    <Icon type="upload" />上传
     </Button>
    </Upload>
 )}
</FormItem>
3//获取上传token
async componentDidMount() {
    await this.initOSS();

  }
initOSS = async () => {
    return new Promise((resolve, reject) => {
      fetch(API.getStsToken).then(response => response.json())
        .then(json => {
          if (json.code === 0) {
            const OSSData = json.data || {};
            Object.assign(_this.OSSData, OSSData);
            this.store = new OSS({
              region: OSSData.region,
              bucket: OSSData.bucketName,
              accessKeyId: OSSData.accessKeyId,
              accessKeySecret: OSSData.accessKeySecret,
              stsToken: OSSData.securityToken,
              timeout: 1800000, // 30分钟
              refreshSTSToken: async () => {
                const response = await fetch(API.getStsToken);
                const json = await response.json() || {};
                if (json.code == -3) return window.location.href = '/content/login';
                if (json.code == -1) return AModalMethod.error({ content: "系统异常" });
                const OSSData = json.data;
                Object.assign(_this.OSSData, OSSData);
                return {
                  accessKeyId: OSSData.accessKeyId,
                  accessKeySecret: OSSData.accessKeySecret,
                  stsToken: OSSData.securityToken
                }
              },
              refreshSTSTokenInterval: 60 * 120 * 1000
            });
            this.setState({ ossInstantiated: true });
            resolve();
          } else {
            message.error("oss配置异常,请联系管理员");
            reject();
          }
        }).catch(e => {
          message.error("获取OSS配置失败");
          reject();
        });
    })
  }
4//实现上传
handleFileChange = ({ file, fileList, event }) => {
    fileList = [...fileList];
    if (fileList.length > this.maxCount) {
      fileList = fileList.slice(0, this.maxCount);
      message.warning(`最多选择${this.maxCount}个文件`);
    }
    this.setState({ fileList })
  }
beforeUpload = async (file, fileList) => {
    if (file.size > 200 * 1024 * 1024) {
      message.error("单个文件大小不能超过200M");
      return Promise.reject(file);
    }
  }
customRequest = async (option) => {
    const { action, file, onSuccess, onError, onProgress } = option;
    console.log(option)
    const { uid } = file;
    if (this.store) {
      mockFileProgress(file, onProgress, this).start();
      this.store.put(file.filePath, file)
        .then((result) => {
          onSuccess(result.res, file);
          mockFileProgress(file, onProgress, this).end();
        }).catch((error) => {
          onError(error);
          mockFileProgress(file, onProgress, this).end();
          this.setState({
            uploadFileStatus: true,
          })
        });
    }
  }