如何在请求主体中使用ANTD上传组件发送元数据?

huangapple go评论71阅读模式
英文:

How to send metadata with ANTD upload component in the request body?

问题

我有一个antd上传组件,它正在将文件上传到后端(expressjs)。 我想在上传的POST请求中发送一些数据。上传组件中有一个data字段,根据antd的文档,data字段是

上传额外的参数或返回上传额外参数的函数

所以我认为这就是我要找的东西,这是我的代码:

<Upload
    action={config.backend.url + "/file/upload"}
    data={{test:"test"}}
    listType="picture-card"
    fileList={fileList}
    accept={acceptedTypes.join()}
    {...others}
>
</Upload>

显然这不起作用,因为在后端,请求体(request.body)是空的。我不确定我做错了什么,文件成功上传,但我无法在请求的正文中发送一些元数据。我做错了什么,如何在文件上传时发送一些元数据?

非常感谢!

英文:

I have an antd upload component that is uploading the a file to the backend ( expressjs). I want to send some data in the upload post request. There is a data field in the upload component, according to antd documentation the data field is

> Uploading extra params or function which can return uploading extra params

So I thought that's what i was looking for, this is my code

 &lt;Upload
        action={config.backend.url + &quot;/file/upload&quot;}
        data={{test:&quot;test&quot;}}
        listType=&quot;picture-card&quot;
        fileList={fileList}
        accept={acceptedTypes.join()}
        {...others}
      &gt;
      &lt;/Upload&gt;

Apparently this doesnt work because in the backend, the request.body is empty. I am not sure what im doing wrong, the file is uploaded sucessfully but i m not able to send some metadata in the body of the request. What am i doing wrong and how can i send some metadata alongside the file upload ?

Thank you so much

答案1

得分: 0

可以使用像@NoNam4说的自定义请求,但是Antd上传组件有一个data属性,你可以使用它来传递参数。

问题在于我之前在使用express的body解析器,它不会解析表单数据并且不能处理多部分体

所以我将这段代码改成了:

import multer from "multer"

app.use(express.urlencoded());
app.use(express.json());
app.use(multer().array());

基本上,multer会处理表单数据类型并将其解析到req.body中。

英文:

It is possible to use custom request like @NoNam4 said, But Antd upload component has data props and you can use it pass params.

The problem is that I was using express body parser which does not parse form-data and does not handle multipart bodies.

So I changed this

app.use(express.urlencoded());
app.use(express.json());

to this

import multer from &quot;multer&quot;

app.use(express.urlencoded());
app.use(express.json());
app.use(multer().array());

Basically multer is handling the form-data type and parsing it to req.body

huangapple
  • 本文由 发表于 2023年6月30日 00:48:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定