antdアップロードファイルOSS

20017 ワード

パッケージ:
import React from 'react';
import {
      Upload, message, Button } from 'antd';
import {
      UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
class AliyunOSSUpload extends React.Component {
     
  state = {
     
    OSSData: {
     },
  };

  async componentDidMount() {
     
    await this.init();
  }

  init = async () => {
     
    try {
     
      const OSSData = await this.mockGetOSSData();
      this.setState({
     
        OSSData,
      });
    } catch (error) {
     
      message.error(error);
    }
  };

  mockGetOSSData = async () => {
     
    const {
      data } = await axios('/api/getNewWebImageToken', {
     
      params: {
     
        t: Date.now(),
      },
    });
    return {
      ...data, dir: '' };
  };

  onChange = ({
      fileList }) => {
     
    const {
      onChange } = this.props;
    if (onChange) {
     
      onChange([...fileList]);
    }
  };

  onRemove = (file) => {
     
    const {
      value, onChange } = this.props;
    const files = value.filter((v) => v.url !== file.url);
    if (onChange) {
     
      onChange(files);
    }
  };

  transformFile = (file) => {
     
    const {
      OSSData } = this.state;
    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = Date.now() + suffix;
    const filekey = OSSData.dir + filename;
    file.url = 'https://img.cancangroup.com/' + filekey;
    file.key = filekey;
    return file;
  };

  getExtraData = (file) => {
     
    const {
      OSSData } = this.state;

    return {
     
      key: file.key,
      OSSAccessKeyId: OSSData.accessid,
      policy: OSSData.policy,
      Signature: OSSData.signature,
      //   success_action_status:200
    };
  };

  beforeUpload = async () => {
     
    const {
      OSSData } = this.state;
    const expire = OSSData.expire * 1000;

    if (expire < Date.now()) {
     
      await this.init();
    }
    return true;
  };

  render() {
     
    const {
      value } = this.props;
    const props = {
     
      name: 'file',
      fileList: value,
      action: this.state.OSSData.host,
      onChange: this.onChange,
      onRemove: this.onRemove,
      transformFile: this.transformFile,
      data: this.getExtraData,
      beforeUpload: this.beforeUpload,
    };
    return (
      <Upload {
     ...props}>
        <Button>
          <UploadOutlined />  
        </Button>
      </Upload>
    );
  }
}
export default AliyunOSSUpload;


次の操作を行います.
<Form.Item name="expensePics">
  <AliyunOSSUpload onChange={
     setfileList} />
</Form.Item>
//  :
 const list = arr.map((key) => {
     
  return {
     
     key,
     uid: key,
     name: key,
     status: 'done',
     url: 'https://img.cancangroup.com/' + key,
   };
 });
 setfileList(list);
 formModalEdit.setFieldsValue({
      expensePics: list });