Created
June 4, 2009 19:13
-
-
Save teejayvanslyke/123783 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
gem 'mime-types' | |
require 'mime/types' | |
require 'uri' | |
module Multipart | |
CRLF = "\r\n" | |
RESERVED_CHARACTERS = /[^a-zA-Z0-9\-\.\_\~]/ | |
def http_multipart_data(params) | |
body = "" | |
headers = {} | |
boundary = Time.now.to_i.to_s(16) | |
headers["Content-Type"] = "multipart/form-data; boundary=#{boundary}" | |
params.each do |key,value| | |
esc_key = URI::escape(key.to_s, RESERVED_CHARACTERS) | |
body << "--#{boundary}#{CRLF}" | |
if value.respond_to?(:read) | |
mime_type = MIME::Types.type_for(value.path)[0] || MIME::Types["application/octet-stream"][0] | |
body << "Content-Disposition: form-data; name=\"#{esc_key}\"; filename=\"#{File.basename(value.path)}\"#{CRLF}" | |
body << "Content-Type: #{mime_type.simplified}#{CRLF*2}" | |
body << value.read | |
else | |
body << "Content-Disposition: form-data; name=\"#{esc_key}\"#{CRLF*2}#{value}" | |
end | |
end | |
body << "--#{boundary}--#{CRLF*2}" | |
headers["Content-Length"] = body.size.to_s | |
return body, headers | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment