且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Antd上传操作将图像上传到Firebase存储时出现问题

更新时间:2023-01-06 17:27:24

您可以使用customRequest属性来解决此问题.看看

You can use customRequest prop to fix this issue. Have a look

class CustomUpload extends Component {
  state = { loading: false, imageUrl: '' };
  
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false
      }));
    }
  };

  beforeUpload = (file) => {
    const isImage = file.type.indexOf('image/') === 0;
    if (!isImage) {
      AntMessage.error('You can only upload image file!');
    }
    
    // You can remove this validation if you want
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      AntMessage.error('Image must smaller than 5MB!');
    }
    return isImage && isLt5M;
  };

  customUpload = ({ onError, onSuccess, file }) => {
    const storage = firebase.storage();
    const metadata = {
        contentType: 'image/jpeg'
    }
    const storageRef = await storage.ref();
    const imageName = generateHashName(); //a unique name for the image
    const imgFile = storageRef.child(`Vince Wear/${imageName}.png`);
    try {
      const image = await imgFile.put(file, metadata);
      onSuccess(null, image);
    } catch(e) {
      onError(e);
    }
  };
  
  render () {
    const { loading, imageUrl } = this.state;
    const uploadButton = (
    <div>
      <Icon type={loading ? 'loading' : 'plus'} />
      <div className="ant-upload-text">Upload</div>
    </div>
    );
    return (
      <div>
        <Upload
          name="avatar"
          listType="picture-card"
          className="avatar-uploader"
          beforeUpload={this.beforeUpload}
          onChange={this.handleChange}
          customRequest={this.customUpload}
        >
          {imageUrl ? <img src={imageUrl} alt="avatar" /> : uploadButton}
        </Upload>
      </div>
    );
  }
}