首页 > 解决方案 > 上传完成后是否可以从 Antd 的上传动作中获取 API 响应?

问题描述

我正在使用 Antd 的上传组件来处理我的图像上传到 Cloudinary。上传文件时,它会返回有关文件的详细信息,其中包括服务器上的文件 URL。在 Antd 的 Upload 组件完成上传后,我需要从响应中获取该文件 URL,知道我该怎么做吗?

还是我需要通过编写自己的自定义请求来自己处理?

标签: reactjsuploadnext.jsantd

解决方案


Ant Design 的上传组件暴露的 onChange 函数在其 prop 中包含了一些关于上传的数据。

您可以使用该file.response属性来检索从您的上传服务返回的响应。

请参阅Ant Design 文档中的以下内容:

{
  file: {
     uid: 'uid',      // unique identifier, negative is recommend, to prevent interference with internal generated id
     name: 'xx.png',   // file name
     status: 'done', // options:uploading, done, error, removed. Intercepted file by beforeUpload don't have status field.
     response: '{"status": "success"}', // response from server
     linkProps: '{"download": "image"}', // additional html props of file link
     xhr: 'XMLHttpRequest{ ... }', // XMLHttpRequest Header
  },
  fileList: [ /* ... */ ],
  event: { /* ... */ },
}

上传组件文档的第一个示例中提供了如何实现 onChange 函数的示例。

const props = {
  name: 'file',
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  headers: {
    authorization: 'authorization-text',
  },
  onChange(info) {
    if (info.file.status === 'done') {
        // Handle response from API
        console.log(info.file.response);
    }
  },
};

return (
    <Upload {...props}>
        <Button icon={<UploadOutlined />}>Click to Upload</Button>
    </Upload>
)

推荐阅读