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

问题描述 投票:3回答:1

我正在使用antd picture-wall/card示例使用此reference code将图像上传到我的firebase存储区,而我唯一要改变的地方是action组件上的<Upload>属性。

action属性上,我正在使用一个将图像上传到firebase存储而不是链接的函数,这两个文件都被接受,如文档中所示。

我的动作功能看起来像这样;

export async function uploadImage(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`)
    return imgFile.put(file, metadata)
}

问题来了,图像成功上传到firebase,但我不断得到antd响应处理错误,并且可能不确定action函数应该返回什么,即使在文档中写入它应该返回一个promise。

错误信息:

XML Parsing Error: syntax error
Location: http://localhost:3000/[object%20Object]
Line Number 1, Column 1:

错误在上传的图像缩略图上也显示为红色边框。

请求帮助,我的动作函数应该返回什么以消除错误。我可以解析我的firebase响应并将必要的详细信息返回给antd上传操作。

运用

    "antd": "^3.9.2",
    "firebase": "^5.8.5",
    "react": "^16.7.0",
javascript reactjs firebase firebase-storage antd
1个回答
1
投票

您可以使用customRequest prop来解决此问题。看一看

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>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.