Module: Rack::Utils::Multipart

Defined in:
lib/rack/utils.rb

Overview

A multipart form data parser, adapted from IOWA.

Usually, Rack::Request#POST takes care of calling this.

Constant Summary collapse

EOL =
"\r\n"

Class Method Summary collapse

Class Method Details

.parse_multipart(env) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/rack/utils.rb', line 168

def self.parse_multipart(env)
  unless env['CONTENT_TYPE'] =~
      %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)\"?|n
    nil
  else
    boundary = "--#{$1}"

    params = {}
    buf = ""
    content_length = env['CONTENT_LENGTH'].to_i
    input = env['rack.input']

    boundary_size = boundary.size + EOL.size
    bufsize = 16384

    content_length -= boundary_size

    status = input.read(boundary_size)
    raise EOFError, "bad content body"  unless status == boundary + EOL

    rx = /(?:#{EOL})?#{Regexp.quote boundary}(#{EOL}|--)/

    loop {
      head = nil
      body = ''
      filename = content_type = name = nil

      until head && buf =~ rx
        if !head && i = buf.index("\r\n\r\n")
          head = buf.slice!(0, i+2) # First \r\n
          buf.slice!(0, 2)          # Second \r\n

          filename = head[/Content-Disposition:.* filename="?([^\";]*)"?/ni, 1]
          content_type = head[/Content-Type: (.*)\r\n/ni, 1]
          name = head[/Content-Disposition:.* name="?([^\";]*)"?/ni, 1]

          if filename
            body = Tempfile.new("RackMultipart")
            body.binmode
          end

          next
        end

        # Save the read body part.
        if head && (boundary_size+4 < buf.size)
          body << buf.slice!(0, buf.size - (boundary_size+4))
        end

        c = input.read(bufsize < content_length ? bufsize : content_length)
        raise EOFError, "bad content body"  if c.nil? || c.empty?
        buf << c
        content_length -= c.size
      end

      # Save the rest.
      if i = buf.index(rx)
        body << buf.slice!(0, i)
        buf.slice!(0, boundary_size+2)

        content_length = -1  if $1 == "--"
      end

      if filename
        body.rewind
        data = {:filename => filename, :type => content_type,
                :name => name, :tempfile => body, :head => head}
      else
        data = body
      end

      if name
        if name =~ /\[\]\z/
          params[name] ||= []
          params[name] << data
        else
          params[name] = data
        end
      end

      break  if buf.empty? || content_length == -1
    }

    params
  end
end