2 # Copyright (c) 2007-2013 Nick Sieger.
3 # See the file README.txt included with the distribution for
4 # software license details.
9 def self.new(boundary, name, value, headers = {})
10 headers ||= {} # avoid nil values
12 FilePart.new(boundary, name, value, headers)
14 ParamPart.new(boundary, name, value, headers)
19 value.respond_to?(:content_type) && value.respond_to?(:original_filename)
33 def initialize(boundary, name, value, headers = {})
34 @part = build_part(boundary, name, value, headers)
35 @io = StringIO.new(@part)
42 def build_part(boundary, name, value, headers = {})
44 part << "--#{boundary}\r\n"
45 part << "Content-Disposition: form-data; name=\"#{name.to_s}\"\r\n"
46 part << "Content-Type: #{headers["Content-Type"]}\r\n" if headers["Content-Type"]
48 part << "#{value}\r\n"
52 # Represents a part to be filled from file IO.
56 def initialize(boundary, name, io, headers = {})
57 file_length = io.respond_to?(:length) ? io.length : File.size(io.local_path)
58 @head = build_head(boundary, name, io.original_filename, io.content_type, file_length,
59 io.respond_to?(:opts) ? io.opts.merge(headers) : headers)
61 @length = @head.bytesize + file_length + @foot.length
62 @io = CompositeReadIO.new(StringIO.new(@head), io, StringIO.new(@foot))
65 def build_head(boundary, name, filename, type, content_len, opts = {}, headers = {})
66 trans_encoding = opts["Content-Transfer-Encoding"] || "binary"
67 content_disposition = opts["Content-Disposition"] || "form-data"
70 part << "--#{boundary}\r\n"
71 part << "Content-Disposition: #{content_disposition}; name=\"#{name.to_s}\"; filename=\"#{filename}\"\r\n"
72 part << "Content-Length: #{content_len}\r\n"
73 if content_id = opts["Content-ID"]
74 part << "Content-ID: #{content_id}\r\n"
77 if headers["Content-Type"] != nil
78 part << "Content-Type: " + headers["Content-Type"] + "\r\n"
80 part << "Content-Type: #{type}\r\n"
83 part << "Content-Transfer-Encoding: #{trans_encoding}\r\n"
88 # Represents the epilogue or closing boundary.
91 def initialize(boundary)
92 @part = "--#{boundary}--\r\n\r\n"
93 @io = StringIO.new(@part)