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

IT技术 javascript reactjs firebase firebase-storage antd
2021-05-05 11:49:29

我正在使用 antd图片墙/卡片示例通过此参考代码将图像上传到我的 firebase 存储,我更改的唯一地方是组件上的action属性<Upload>

在该action属性上,我正在使用一个将图像上传到 firebase 存储的函数,而不是一个链接,两者都被接受,如 docs 所示

我的动作函数看起来像这样;

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",
2个回答

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

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>
    );
  }
}

只是留在这里以防万一有人也想跟踪文件的进度

 const customUpload = async ({ onError, onSuccess, file, onProgress }) => {
    let fileId = uuidv4()
    const fileRef = stg.ref('demo').child(fileId)
    try {
      const image = fileRef.put(file, { customMetadata: { uploadedBy: myName, fileName: file.name } })

      image.on(
        'state_changed',
        (snap) => onProgress({ percent: (snap.bytesTransferred / snap.totalBytes) * 100 }),
        (err) => onError(err),
        () => onSuccess(null, image.metadata_)
      )
    } catch (e) {
      onError(e)
    }
  }