最好将文件和相关数据作为 JSON 发布到 RESTful WebService [英] Posting a File and Associated Data to a RESTful WebService preferably as JSON

查看:33
本文介绍了最好将文件和相关数据作为 JSON 发布到 RESTful WebService的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能会是一个愚蠢的问题,但我正在度过那些夜晚.在一个应用程序中,我正在开发 RESTful API,我们希望客户端将数据作为 JSON 发送.此应用程序的一部分要求客户端上传文件(通常是图像)以及有关图像的信息.

This is probably going to be a stupid question but I'm having one of those nights. In an application I am developing RESTful API and we want the client to send data as JSON. Part of this application requires the client to upload a file (usually an image) as well as information about the image.

我很难在单个请求中追踪这种情况是如何发生的.是否可以将文件数据 Base64 转换为 JSON 字符串?我需要向服务器发送 2 个帖子吗?我不应该为此使用 JSON 吗?

I'm having a hard time tracking down how this happens in a single request. Is it possible to Base64 the file data into a JSON string? Am I going to need to perform 2 posts to the server? Should I not be using JSON for this?

顺便提一下,我们在后端使用 Grails,这些服务可由本地移动客户端(iPhone、Android 等)访问,如果其中任何一个有所不同.

As a side note, we're using Grails on the backend and these services are accessed by native mobile clients (iPhone, Android, etc), if any of that makes a difference.

推荐答案

我在这里问了一个类似的问题:

I asked a similar question here:

我该怎么做使用 REST 网络服务上传带有元数据的文件?

你基本上有三个选择:

  1. Base64 对文件进行编码,代价是数据大小增加了约 33%,并增加了服务器和客户端的编码/解码处理开销.
  2. 首先在 multipart/form-data POST 中发送文件,然后将 ID 返回给客户端.然后客户端发送带有 ID 的元数据,服务器重新关联文件和元数据.
  3. 先发送元数据,然后返回一个 ID 给客户端.然后客户端发送带有 ID 的文件,服务器重新关联文件和元数据.
  1. Base64 encode the file, at the expense of increasing the data size by around 33%, and add processing overhead in both the server and the client for encoding/decoding.
  2. Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.
  3. Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.

这篇关于最好将文件和相关数据作为 JSON 发布到 RESTful WebService的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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