使用 antd 将 React 中的图像上传到 DRF

发布于 2025-01-16 01:21:50 字数 2177 浏览 2 评论 0原文

我正在尝试使用 antd 从 React 前端将包含图像的表单上传到我的 DRF API。提交表单时,我遇到来自 DRF 的以下错误

{
  "photo": [
    "The submitted data was not a file. Check the encoding type on the form."
  ]
}

这是当我检查提交的值时在“照片”下收到的值

"photo":[{"uid":"rc-upload-1647817573720-2","lastModified":1643547530011,"lastModifiedDate":"2022-01-30T12:58:50.011Z","name":"chibi spiderman.jpg","size":445488,"type":"image/jpeg","percent":0,"originFileObj":{"uid":"rc-upload-1647817573720-2"},"error":{"status":404,"method":"post","url":""},"response":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST /app/new-individual</pre>\n</body>\n</html>\n","status":"error"}]

我的 API 设置良好,我相信问题主要与我在提交之前处理表单数据有关以正确满足图像上传的需要。但如果您不需要查看我的 API 代码,请告诉我。这是我的前端代码

我的表单项用于表单中的图像


<Form.Item
  name="photo"
  label = "Your Photo"
  valuePropName="fileList"
  getValueFromEvent={normFile}
>
  <Upload name='photo'>
    <Button icon={<UploadOutlined />}>Click to Upload</Button>
  </Upload>
</Form.Item>

功能处理表单的提交

const onFinish = values => {
    values["date_of_birth"] = moment(values.date_of_birth).format("YYYY-MM-DD")
    if(values["dependants"] !== undefined){
        values["dependants"].forEach(d => {
            d["date_of_birth"] = moment(d.date_of_birth).format("YYYY-MM-DD")
        });
    }
    console.log(JSON.stringify(values))
    const userToken = localStorage.getItem(AUTH_TOKEN)
    IndividualService.setToken(userToken)

    IndividualService.postIndividual(values).then(resp => {
        console.log(resp.individual_details)
        setIndividual(resp.individual_details)
        form.resetFields()
        localStorage.setItem("individualPlan", resp.individual_details.id)
        setSubmitted(true)
        message.success('successfully added details for Individual plan')

    }).catch(error => {
        message.error('Error occured, plase try again', error.message)
      })
    
  };


I'm trying to upload a form inclusive of an Image to my DRF API from a react frontend using antd. On submitting the form I encounter the following error from DRF

{
  "photo": [
    "The submitted data was not a file. Check the encoding type on the form."
  ]
}

This is the value received under "photo" when I check the values being submitted

"photo":[{"uid":"rc-upload-1647817573720-2","lastModified":1643547530011,"lastModifiedDate":"2022-01-30T12:58:50.011Z","name":"chibi spiderman.jpg","size":445488,"type":"image/jpeg","percent":0,"originFileObj":{"uid":"rc-upload-1647817573720-2"},"error":{"status":404,"method":"post","url":""},"response":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot POST /app/new-individual</pre>\n</body>\n</html>\n","status":"error"}]

My API is set up well and I believe the issue is mainly revolving around my handling of the form data before submitting to properly cater for the Image upload. But incase you need t view my code for the API just let me know. Here's a look at my frontend code

My Form item for the image within the form


<Form.Item
  name="photo"
  label = "Your Photo"
  valuePropName="fileList"
  getValueFromEvent={normFile}
>
  <Upload name='photo'>
    <Button icon={<UploadOutlined />}>Click to Upload</Button>
  </Upload>
</Form.Item>

Function handling submit for the form

const onFinish = values => {
    values["date_of_birth"] = moment(values.date_of_birth).format("YYYY-MM-DD")
    if(values["dependants"] !== undefined){
        values["dependants"].forEach(d => {
            d["date_of_birth"] = moment(d.date_of_birth).format("YYYY-MM-DD")
        });
    }
    console.log(JSON.stringify(values))
    const userToken = localStorage.getItem(AUTH_TOKEN)
    IndividualService.setToken(userToken)

    IndividualService.postIndividual(values).then(resp => {
        console.log(resp.individual_details)
        setIndividual(resp.individual_details)
        form.resetFields()
        localStorage.setItem("individualPlan", resp.individual_details.id)
        setSubmitted(true)
        message.success('successfully added details for Individual plan')

    }).catch(error => {
        message.error('Error occured, plase try again', error.message)
      })
    
  };


如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文