文件上传

文件上传

Upload

图片上传

class UploadThumb extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      imageUrl: ""
    };
  }

  handleChange(info) {
    if (info.file.status === "uploading") {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrl =>
        this.setState({ imageUrl, loading: false })
      );
    }
  }

  getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  beforeUpload(file) {
    const isJPG = file.type === "image/jpeg";
    if (!isJPG) {
      message.error("You can only upload JPG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJPG && isLt2M;
  }

  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? "loading" : "plus"} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );

    return (
      <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="/upload"
        beforeUpload={this.beforeUpload.bind(this)}
        onChange={this.handleChange.bind(this)}
      >
        {this.state.imageUrl ? (
          <img src={this.state.imageUrl} alt="" />
        ) : (
          uploadButton
        )}
      </Upload>
    );
  }
}

文件转换

const props = {
  action: "https://www.mocky.io/v2/5cc8019d300000980a055e76",
  transformFile(file) {
    return new Promise(resolve => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        const canvas = document.createElement("canvas");
        const img = document.createElement("img");
        img.src = reader.result;
        img.onload = () => {
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0);
          ctx.fillStyle = "red";
          ctx.textBaseline = "middle";
          ctx.fillText("Ant Design", 20, 20);
          canvas.toBlob(resolve);
        };
      };
    });
  }
};

ReactDOM.render(
  <div>
    <Upload {...props}>
      <Button>
        <Icon type="upload" /> Upload
      </Button>
    </Upload>
  </div>,
  mountNode
);
上一页
下一页