Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohamadaliakbari/3ec5ac08013f75b57a032ef952596b0d to your computer and use it in GitHub Desktop.
Save mohamadaliakbari/3ec5ac08013f75b57a032ef952596b0d to your computer and use it in GitHub Desktop.
Structure of multi-part data form request

There are a few ways to accomplish posting a photo from an iPhone or iPad to a REST API but the method I’ve found to be the most useful is to create a multi-part form request for the task.

It would be nice to just send the byte stream up on its own, but typically you need to attach some other models or data to the request so that you know what context to place the image into on the server. Borrowing from good old HTML Forms, this method will allow you to submit a whole bunch of data in a variety of formats in a single shot.

As well as this works, there is something unpleasant about generating a multi-part form request for iOS. It’s a specific structure like any other data format, but it’s got some peculiarities that make it feel...hackish. Here is an example of a multi-part form request so you can see what will ultimately be generated:

POST /path/to/script.php HTTP/1.0
Host: example.com
Content-type: multipart/form-data, boundary=AaB03x
Content-Length: $requestlen

--AaB03x
content-disposition: form-data; name="field1"

$field1
--AaB03x
content-disposition: form-data; name="field2"

$field2
--AaB03x
content-disposition: form-data; name="userfile"; filename="$filename"
Content-Type: $mimetype
Content-Transfer-Encoding: binary


$binarydata
--AaB03x--

The boundary string is a unique string that will not appear in your data and will be used to separate out the different parts of your request. You can see how --AaB03x is used to indicate the start of a new form part and --AaB03x-- is used to signal the end of the request. Your image(s) will reside where the $binarydata placeholder is.

https://www.itworld.com/article/2702129/development/how-to-upload-photos-from-ios-to-a-rest-api.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment