Rack::MultipartRelated it's a rack middleware to parse multipart/related requests and rebuild a simple/merged parameters hash.
When a ruby webserver receives a multipart/related request:
POST /users HTTP/1.1
Content-Type: multipart/related; boundary="the_boundary"; type="application/json"; start="json"
--the_boundary
Content-Type: application/json; charset=UTF-8
Content-Disposition: inline; name="json"\r
{"user":{"name": "Jhon", "avatar": "cid:avatar_image" }}
--the_boundary
Content-Type: image/png
Content-Disposition: inline; name="avatar_image"; filename="avatar.png"
<the binary content of image comes here>
--the_boundary--
The parameters hash arrives like this:
{
"json" => {
:type => "application/json; charset=UTF-8",
:tempfile => <File:/var/folders/Iu/IuwHUNlZE8OaYMACfwiapE+++TI/-Tmp-/RackMultipart20101217-30578-l17vkd-0>, # The json content
:head => "Content-Type: application/json; charset=UTF-8\r\nContent-Disposition: inline; name=\"json\"\r\n",
:name => "json"
},
"avatar_image" => {
:type => "image/png",
:filename =>"image.png",
:tempfile => <File:/var/folders/Iu/IuwHUNlZE8OaYMACfwiapE+++TI/-Tmp-/RackMultipart20101217-30578-bt18q9-0>, # The binary content of image
:head => "Content-Type: image/gif\r\nContent-Disposition: inline; name=\"avatar_image\"; filename=\"image.png\"\r\n",
:name =>"avatar_image"
}
}
Pay attention that the second part of the 'request' (in our example, "avatar_image") needs to be referenced in the first part (in the example, "json") as "cid:REFERENCE_NAME_OF_THE_SECOND_PART"
Using this middleware, the hash above is parsed and rebuilt like the code below:
{
"user" => {
"name" => "Jhon",
"avatar" => {
:type => "image/png",
:filename =>"image.png",
:tempfile => <File:/var/folders/Iu/IuwHUNlZE8OaYMACfwiapE+++TI/-Tmp-/RackMultipart20101217-30578-bt18q9-0>, # The binary content of image
:head => "Content-Type: image/gif\r\nContent-Disposition: inline; name=\"avatar_image\"; filename=\"image.png\"\r\n",
:name =>"avatar_image"
}
}
}
In your Gemfile:
gem 'rack-multipart_related'
In your environment.rb:
require 'rack/multipart_related'
config.middleware.use Rack::MultipartRelated
Just 'use Rack::MultipartRelated' as any other middleware
At this moment, this middleware only supports JSON in the start part.
- Support other formats to start part, like XML.