Post files and related data to RESTful WebService in JSON format
P粉056618053
2023-08-20 13:47:10
<p>In the application I'm developing, we want the client to send data in JSON format, so I'm developing a RESTful API. Part of the application requires the client to upload a file (usually an image), along with information about the image. </p>
<p>I'm having trouble tracking down how to accomplish this in a single request. Is it possible to Base64 encode file data into a JSON string? Do I need to perform two POST requests to the server? Shouldn't I be using JSON to handle this? </p>
<p>Also, we use Grails on the backend, and these services are accessible by native mobile clients (iPhone, Android, etc.), if that information is different. </p>
You can send files and data in one request using the multipart/form-data content type:
From http://www.faqs.org/rfcs/rfc2388.html:
You can include file information or field information in each section between each boundary. I have successfully implemented a RESTful service that requires users to submit data and forms, multipart/form-data works perfectly. The service is built using Java/Spring and the client uses C#, so unfortunately I don't have a Grails example to give you on how to set up the service. In this case you don't need to use JSON as each "form-data" section gives you a place to specify the parameter names and their values.
The benefit of using multipart/form-data is that you are using the headers defined by HTTP, so you follow the REST philosophy of using existing HTTP tools to create services.
I asked a similar question here:
How to upload files with metadata using REST web service?
You basically have three options:
multipart/form-data
and return the ID to the client. The client then sends metadata using that ID, and the server reassociates the file and metadata.