简体   繁体   English

在单个 HTTP POST 请求中同时传递文件资源和 json 主体

[英]Passing both a file resource and a json body in a single HTTP POST request

I'm building a REST API and I have an endpoint where I need to pass both a file resource, and a JSON body.我正在构建一个 REST API 并且我有一个端点,我需要传递一个文件资源和一个 JSON 主体。 Apparently I cannot do it:显然我不能这样做:

You can only select one HTTP request method! You asked for both POST.

I'm getting this error when in cURL request I provide both form field and a body like this:在 cURL 请求中,我收到了这个错误,我同时提供了表单字段和这样的正文:

curl -X POST "http://127.0.0.1/path" -F "resource=@img.jpg" -d "@requestBody.json"

If I want this to work, I need to pass my request body as a form field itself:如果我想让它工作,我需要将我的请求正文作为表单字段本身传递:

curl -X POST "http://127.0.0.1/path" -F "resource=@img.jpg" -F "myRequestBody=@requestBody.json;type=application/json"

The thing is that in order to fetch this down the line, I need to use file_get_contents() function and then json decode the content as well.问题是,为了得到这个,我需要使用file_get_contents() function 然后 json 解码内容。 It's not a nice solution, and it seems a bit slow.这不是一个很好的解决方案,而且似乎有点慢。 Is there a cleaner way to do it?有更清洁的方法吗?

Depending on how big the file is, you could base64 encode the data and include that in your JSON payload.根据文件的大小,您可以 base64 对数据进行编码并将其包含在您的 JSON 有效负载中。

Otherwise, you will need to use Content-Type: multipart/form-data .否则,您将需要使用Content-Type: multipart/form-data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM