Skip to content

class HTTP::FormData::Builder
inherits Reference

Builds a multipart/form-data message.

Example

require "http"

io = IO::Memory.new
builder = HTTP::FormData::Builder.new(io, "aA47")
builder.field("name", "joe")
file = IO::Memory.new("file contents")
builder.file("upload", file, HTTP::FormData::FileMetadata.new(filename: "test.txt"))
builder.finish
io.to_s # => "--aA47\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\njoe\r\n--aA47\r\nContent-Disposition: form-data; name=\"upload\"; filename=\"test.txt\"\r\n\r\nfile contents\r\n--aA47--"

Class methods

.new(io : IO, boundary = MIME::Multipart.generate_boundary)

Creates a new FormData::Builder which writes to io, using the multipart boundary boundary.

View source

Methods

#boundary : String

View source

#content_type

Returns a content type header with correct boundary parameter.

builder = HTTP::FormData::Builder.new(io, "a4VF")
builder.content_type # => "multipart/form-data; boundary=\"a4VF\""
View source

#field(name : String, value, headers : HTTP::Headers = HTTP::Headers.new)

Adds a form part with the given name and value. Headers can optionally be provided for the form part.

View source

#file(name : String, io, metadata : FileMetadata = FileMetadata.new, headers : HTTP::Headers = HTTP::Headers.new)

Adds a form part called name, with data from io as the value. Metadata can be provided to add extra metadata about the file to the Content-Disposition header for the form part. Other headers can be added using headers.

View source

#finish

Finalizes the multipart message, this method must be called before the generated multipart message written to the IO is considered valid.

View source