Home  >  Q&A  >  body text

Post files and related data to RESTful WebService in JSON format

<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>
P粉056618053P粉056618053447 days ago572

reply all(2)I'll reply

  • P粉994092873

    P粉9940928732023-08-21 12:54:55

    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.

    reply
    0
  • P粉145543872

    P粉1455438722023-08-21 11:24:16

    I asked a similar question here:

    How to upload files with metadata using REST web service?

    You basically have three options:

    1. Base64 encode the file, but increases the data size by about 33% and adds encoding/decoding processing overhead in the server and client.
    2. First send the file in the form of 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.
    3. Send metadata first and return the ID to the client. The client then sends the file using that ID, and the server reassociates the file and metadata.

    reply
    0
  • Cancelreply