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

查看:32
本文介绍了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 发送文件和 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).

问题

  • 是否可以在同一个请求中向 API 发送 JSON 数据和文件?如果是这样,我该如何使用 curl 或 REST 控制台(chrome 扩展程序)
  • 这个请求的 contentType 是什么?
  • 如果这意味着我可以在同一个请求中发送文件和其他数据(字符串),我愿意以另一种格式发送数据.我没有被 JSON 束缚

更新

我发现了另一个问题这是问同样的事情.从 该问题的答案 看来,似乎只有三个选择,而且没有一个说可以同时发送 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 和 Image 及其相应的正确 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天全站免登陆