Is using multipart/form-data any better then JSON + Base64?

15,577

Should I just have the client upload JSON with the fields encoded in base64, and take the 25% hit?

The hit will be 33% since 4/3=1.33.

Or should I have the JSON object being represented as some sort of "json" variable in a Multipart/form-data request, and have the binary files to be uploaded as another variable?

This should work.

You might also consider this approach: send all files using multipart, then get some identificators of files as a response. Put this identificators in your json and send it anyway you like. This approach might be beneficial if you have many scenarios in which you send files: you might always send them to the server with the same request, then get their identificators; after that do with them what you like.

Share:
15,577

Related videos on Youtube

genixpro
Author by

genixpro

I am a computer programmer and entrepreneurs.

Updated on June 14, 2022

Comments

  • genixpro
    genixpro almost 2 years

    I have a server and I need to upload files along with some fields from the client to the server. I have currently been using standard multipart/form-data.

    I have found however that using multipart/form-data is not ideal. Objects on my server may have other objects nested within them, and thus are represented as a JSON object with other JSON objects embedded within.

    I would like for the client to start making POST/PUT requests using a JSON representation exactly like it would expect in a GET request to the server, in a REST-ful manner. This way I don't have to flatten the fields which might be nested a couple layers within the JSON object in order to use multipart/form-data.

    Problem is, JSON doesn't represent binary data. Multipart/form-data doesn't seem to have a way to represent fields nested within the values of other fields. But it does have much better handling of file-uploads.

    I am at a loss for how to design this. Should I just have the client upload JSON with the fields encoded in base64, and take the 25% hit? Or should I have the JSON object being represented as some sort of "json" variable in a Multipart/form-data request, and have the binary files to be uploaded as another variable?

  • Satya Kalluri
    Satya Kalluri over 9 years
    The last approach advocating separate calls (one for the Multipart image and another for the JSON data) is interesting. The only concern being 2 API calls instead of one. Ofcourse, this trade off is app-specific.
  • Surya Pratap
    Surya Pratap almost 3 years
    a bit late to say this, but if you go the 2 API call route, you will also need to handle orphan file cleanup where a file call is successful but the subsequent json call did not occur.