HTTP.FormData (http_fetch v0.5.0)

Handles HTTP form data and multipart/form-data encoding for file uploads. Supports both regular form data and multipart uploads with streaming file support.

Summary

Functions

Adds a form field.

Generates a random boundary for multipart/form-data.

Gets the appropriate Content-Type header for the form data.

Creates a new empty FormData struct.

Converts FormData to HTTP body content with appropriate encoding.

Types

form_part()

@type form_part() ::
  {:field, String.t(), String.t()}
  | {:file, String.t(), String.t(), String.t(), File.Stream.t()}
  | {:file, String.t(), String.t(), String.t(), String.t()}

t()

@type t() :: %HTTP.FormData{boundary: String.t() | nil, parts: [form_part()]}

Functions

append_field(form, name, value)

@spec append_field(t(), String.t(), String.t()) :: t()

Adds a form field.

Examples

iex> HTTP.FormData.new() |> HTTP.FormData.append_field("name", "value")
%HTTP.FormData{parts: [{:field, "name", "value"}], boundary: nil}

append_file(form, name, filename, content, content_type \\ "application/octet-stream")

@spec append_file(
  t(),
  String.t(),
  String.t(),
  File.Stream.t() | String.t(),
  String.t()
) :: t()

Adds a file field for upload with streaming support.

Examples

iex> file_stream = File.stream!("test.txt")
iex> HTTP.FormData.new() |> HTTP.FormData.append_file("upload", "test.txt", file_stream)
%HTTP.FormData{parts: [{:file, "upload", "test.txt", "text/plain", %File.Stream{}}], boundary: nil}

generate_boundary()

@spec generate_boundary() :: String.t()

Generates a random boundary for multipart/form-data.

get_content_type(form_data)

@spec get_content_type(t()) :: String.t()

Gets the appropriate Content-Type header for the form data.

new()

@spec new() :: t()

Creates a new empty FormData struct.

Examples

iex> HTTP.FormData.new()
%HTTP.FormData{parts: [], boundary: nil}

to_body(form)

@spec to_body(t()) ::
  {:url_encoded, String.t()} | {:multipart, String.t(), String.t()}

Converts FormData to HTTP body content with appropriate encoding.

Returns {:url_encoded, body} for regular forms or {:multipart, body, boundary} for multipart.