Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between 'multipart/related' and 'multipart/form-data' and when should I use each?

I was able to find a lot of information about multipart/form-data but not much about multipart/related. In terms of the protocol / request format, can someone explain the differences between these two http specifications when it comes to file uploading?

like image 609
TakeSoUp Avatar asked Oct 10 '16 14:10

TakeSoUp


People also ask

When would you use a multipart?

Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file uploads and for transferring data of several types in a single request (for example, a file along with a JSON object).

Why do we use multipart files?

Multipart requests consist of sending data of many different types separated by a boundary as part of a single HTTP method call. Generally, we can send complicated JSON, XML, or CSV data, as well as transfer multipart file(s) in this request. Examples of multipart files include audio or image files.

What is multipart form data in REST API?

multipart/form-data is often found in web application HTML Form documents and is generally used to upload files. The form-data format is the same as other multipart formats, except that each inlined piece of content has a name associated with it.

How does multi part form data work?

Multipart/form-data is one of the most used enctype/content type. In multipart, each of the field to be sent has its content type, file name and data separated by boundary from other field. No encoding of the data is necessary, because of the unique boundary. The binary data is sent as it is.


1 Answers

multipart/form-data is used to upload files of MIME-compatible representation, such as pictures and video files, and related metadata a single POST request. That's what happens when you fill in a form online with attached pictures and then press the "Submit" button.

multipart/related is used for compound documents and you would need to combine the separate body parts to provide the full meaning of the message. One use case would be submitting some Base64-encoded images together with the associated metadata.

One POST request sample is (https://cloud.google.com/storage/docs/json_api/v1/how-tos/multipart-upload):

POST https://www.googleapis.com/upload/storage/v1/b/myBucket/o?uploadType=multipart HTTP/1.1
Authorization: Bearer [YOUR_AUTH_TOKEN]
Content-Type: multipart/related; boundary=foo_bar_baz
Content-Length: [NUMBER_OF_BYTES_IN_ENTIRE_REQUEST_BODY]

--foo_bar_baz
Content-Type: application/json; charset=UTF-8

{
  "name": "myObject"
}

--foo_bar_baz
Content-Type: image/jpeg

[JPEG_DATA]
--foo_bar_baz--

You can find more details at https://msdn.microsoft.com/en-us/library/ms527355(v=exchg.10).aspx

like image 51
Gongqin Shen Avatar answered Oct 07 '22 17:10

Gongqin Shen