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

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.


    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!

    链接地址: http://www.djcxy.com/p/48644.html

    上一篇: 将JSONArray发布到REST服务

    下一篇: REST API Design将JSON数据和文件发送到同一请求中的api