REST API设计将JSON数据和文件发送到同一请求中的api [英] REST API Design sending JSON data and a file to the api in same request

查看:1036
本文介绍了REST API设计将JSON数据和文件发送到同一请求中的api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在现有应用程序之上创建了一个REST API。其中的一个特性是将json数据和用户上传的文件一起传入。

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.

我不确定如何在同一请求中向REST API发送文件AND json数据?

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

我有json部分工作,我测试使用curl:

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.

我使用的是grails应用程序,所以我在控制器中得到这样的数据: new Foo(params.mydata)

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

问题


  • JSON数据和一个文件在同一个请求中的API?如果是,我该如何使用curl或REST控制台(chrome扩展)

  • 这个请求的 contentType

  • 如果我可以在同一请求中发送文件和其他数据(字符串),我可以使用另一种格式发送数据。我没有绑定JSON

更新

我发现另一个SO问题这是问同样的事情。从该问题的答案,似乎只有三个选择,没有一个说它可能发送两个,json数据和文件,在同一请求。

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.

推荐答案

我认为这是一个非常令人讨厌的问题,正确的方式来做这是一个多部分消息。这样,你可以发布JSON和图像与它们相应的正确的MIME类型。 维基百科关于多部分MIME类型的文章提供了一个示例。看起来像Apache httpcommons和Jersey都支持这种事情,显然 curl也太!

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!

这篇关于REST API设计将JSON数据和文件发送到同一请求中的api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆