REST API Design sending JSON data and a file to the api in same request

穿精又带淫゛_ 提交于 2019-12-23 12:04:20

问题


I am creating a REST API on top of an existing application. One of the features takes in a json data along with a file uploaded by the user.

I am unsure how to send a file AND json data in the same request to the REST API?

I have the json part working and I test that using curl:

curl -XPOST http://localhost:8080/myapp/foo -d '{"mydata": {
    "name": "somename",
    "gender": "male"
}}'
//I would like to send an image (say, profile image) with the above request as well.

I'm using a grails application so I get this data in my controller like so: new Foo(params.mydata).

Question

  • Is it possible to send JSON data and a file in the same request to the API? If so, how can I do it using curl or REST Console (chrome extension)
  • What would be the contentType of this request?
  • I'm open to sending data in another format if it means that I can send file and other data (strings) within the same request. I'm not tied on JSON

Update

I found another SO question which is asking the same thing. From the answer to that question it seems there are only three choices and none of which say that its possible to send both, json data and file, within the same request. Which is very discouraging...I will keep this question open to see if anyone has other ideas.


回答1:


I think the "right" way to do this is with a multipart message. That way, you can post up both the JSON and the Image with their corresponding correct MIME type. The wikipedia article on multipart mime types has an example of what this would look like. It looks like both Apache httpcommons and Jersey support this sort of thing, and apparently curl does too!



来源:https://stackoverflow.com/questions/16550561/rest-api-design-sending-json-data-and-a-file-to-the-api-in-same-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!