Skip to content

Instantly share code, notes, and snippets.

@hernan43
Created May 6, 2010 20:12
Show Gist options
  • Save hernan43/392644 to your computer and use it in GitHub Desktop.
Save hernan43/392644 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'rubygems'
require 'cgi'
require 'pp'
require 'mime/types'
def mime_type(file)
case
when file =~ /\.jpg/ then 'image/jpg'
when file =~ /\.gif$/ then 'image/gif'
when file =~ /\.png$/ then 'image/png'
else 'application/octet-stream'
end
end
CRLF = "\r\n"
def build_multipart_bodies(*files)
boundary = Time.now.to_i.to_s(16)
body = ""
files.each do |file|
esc_key = CGI.escape("media[]")
body << "--#{boundary}#{CRLF}"
if file.respond_to?(:read)
body << "Content-Disposition: form-data; name=\"#{esc_key}\"; filename=\"#{File.basename(file.path)}\"#{CRLF}"
body << "Content-Type: #{MIME::Types.type_for(file.path).to_s}#{CRLF*2}"
body << file.read
else
body << "Content-Disposition: form-data; name=\"#{esc_key}\"#{CRLF*2}#{file}"
end
body << CRLF
end
body << "--#{boundary}--#{CRLF*2}"
{
:body => body,
:headers => {"Content-Type" => "multipart/form-data; boundary=#{boundary}"}
}
end
f = File.open("tiny.jpg")
pp multipart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment