background

The React Family bucket contains the AntDesign component library, Dva state management, permission modules, internationalization, theme customization, and more. This is not the focus of today.

Upload to OSS using the default Upload mode.

No reason ! Why not !!

!!!!!!!!!! Now the official example and API have been updated, please refer to the official example:

Ant. The design/components /…

The body of the

Go directly to the code, try the code self-explanatory:


import CryptoJS from 'crypto-js';
import Base64 from 'base-64'; . const uploadButton = ( <div> <Icon type={payImgLoading ? 'loading' : 'plus'} /> <div className="ant-upload-text">Upload</div> </div> ); . <Upload action="http://xxxx.oss-cn-shanghai.aliyuncs.com" accept="image/*" listType="picture-card" className="avatar-uploader" showUploadList={false} beforeUpload={this.beforeUpload} onChange={this.handleChange} data={{  key: todayKey + "/${filename}", policy: policyBase64, OSSAccessKeyId: accessKeyId, success_action_status: 200, signature, }} > { payImgUrl ? <img src={imgUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton } </Upload>Copy the code

The above code focuses on the action attribute and data attribute of the Upload component. One is the address of the image Upload interface, and of course it can directly be the ADDRESS of the OSS object storage. The core lies in the data attribute:

  • Key: File path: date folder + file name

/${filename} is a string. Filename is a parameter and cannot be filled with a real filename.

  • policy: policyBase64
const policyText = {
  "expiration": "The 2028-01-01 T12:00:00) 000 z"// Set the expiration time of the Policy"conditions": [["content-length-range", 0, 1048576000] // Set the upload file size limit]}; const policyBase64 = Base64.encode(JSON.stringify(policyText))Copy the code
  • OSSAccessKeyId: Specifies the KEYID of the ARI cloud OSS
  • success_action_status:200
  • Signature: It is recommended to use background signature. The following is the front-end signature method. AccessSecret is the ALI cloud OSS secret key
const bytes = CryptoJS.HmacSHA1(policyBase64, accessSecret, { asBytes: true });
const signature = bytes.toString(CryptoJS.enc.Base64); 
Copy the code

Two cryptographic libraries are used above

import CryptoJS from 'crypto-js'; //"base-64": "^ 0.1.0 from"
import Base64 from 'base-64'; //"crypto-js": "^" 3.1.9-1
Copy the code

Today the editor is always automatically rolling, not wordy, in the configuration of the problem please leave a message…

Benefits, complete code attached

/* eslint-disable no-template-curly-in-string */

import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import CryptoJS from 'crypto-js';
import Base64 from 'base-64';
import {
  Card, Form, Input, Divider, Icon, Upload, message, Button,
  Table, Modal, InputNumber, Select, Popconfirm
} from 'antd';

const todayKey = moment().format('YYYYMMDD');
const host = "http://xxxx.oss-cn-shanghai.aliyuncs.com";
const accessKeyId = "xxxxx";
const accessSecret = "xxxxxx";
const policyText = {
  "expiration": "The 2028-01-01 T12:00:00) 000 z"// Set the expiration time of the Policy."conditions": [["content-length-range", 0, 1048576000] // Set the upload file size limit]}; const policyBase64 = Base64.encode(JSON.stringify(policyText)) const bytes = CryptoJS.HmacSHA1(policyBase64, accessSecret, { asBytes:true });
const signature = bytes.toString(CryptoJS.enc.Base64); 


@Form.create()
@connect(({loading, usermanage }) => ({
  userList: usermanage.userList,
  loading: loading.models.usermanage,
}))
class TableList extends PureComponent {

  state = {
    payImgLoading: false,
    payImgUrl: ' '}; BeforeUpload = (file) => {// Check the image type const isJPG = file.type ==='image/jpeg';
    const isPNG = file.type === 'image/png';
    const isBMP = file.type === 'image/bmp';
    const isGIF = file.type === 'image/gif';
    const isWEBP = file.type === 'image/webp';
    const isPic = isJPG || isPNG || isBMP || isGIF || isWEBP;
    if(! isPic) { message.error('Please upload picture');
      return;
    }
    const isLt5M = file.size / 1024 / 1024 < 5;
    if(! isLt5M) { message.error('Uploads must be less than 5MB! ');
      return;
    }
    return isPic&&isLt5M;
  }

  handleChange = ({ file }) => {
    if (file.status === 'uploading') {
      this.setState({ payImgLoading: true });
      return;
    }
    if (file.status === 'done') {
      this.setState({
        payImgUrl: `${host}/${todayKey}/${file.name}`,
        payImgLoading: false}); }}render() {
    
    const uploadButton = (
      <div>
        <Icon type={payImgLoading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
  
    return (
        <Upload
           action={host}
           accept="image/*"
           listType="picture-card"
           className="avatar-uploader"
           showUploadList={false}
           beforeUpload={this.beforeUpload}
           onChange={this.handleChange}
           data={{
             key: todayKey + "/${filename}",
             policy: policyBase64,
             OSSAccessKeyId: accessKeyId,
             success_action_status: 200,
             signature,
           }}
        >
           {
               payImgUrl ? 
               <img src={payImgUrl} alt="avatar" style={{ width: '100%'}} /> : uploadButton } </Upload> ); }}Copy the code