mime/multipart

mime/multipart writers and readers: part order, fixed boundaries, Close, and size limits, all in memory.

モジュールページの本文は現在英語です。

The mime/multipart package writes and reads multipart MIME messages, including multipart/form-data. Import it as "mime/multipart". A Writer emits parts in the order you create them and finishes the message in Close, which writes the trailing boundary. A Reader returns that same order from NextPart. Skipping Close on the Writer leaves an incomplete message; skipping Close on a Part can delay resource cleanup.

Bound what you read. io.LimitReader can cap an individual part. On a server, wrap the request body with http.MaxBytesReader before constructing a Reader, or use Request.ParseMultipartForm with a maxMemory budget; those APIs live on net/http. This page stays in memory and does not accept uploads from a network.

NewWriter normally chooses a random boundary. The examples call SetBoundary so the output is deterministic. Outputs were recorded with Go 1.24.0.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
multipart.NewWriter, SetBoundary, NewReader, NextPart, and CloseWrite two parts with a fixed boundary, close the writer, then read both parts and close each one.
io.LimitReader on a multipart.PartRead at most four bytes from one in-memory part, then close the part.

Write, close, and read parts in order

CreateFormField and CreateFormFile return writers for the next part. FormDataContentType is a Content-Type value whose boundary parameter can be parsed with mime.ParseMediaType, which is how official documentation says you recover the boundary for NewReader. After Close, NextPart yields title then file, then io.EOF. FormName and FileName identify the part; a non-file field has an empty file name.

multipart.NewWriter, SetBoundary, NewReader, NextPart, and Close

func NewWriter(w io.Writer) *Writer
func (w *Writer) SetBoundary(boundary string) error
func (w *Writer) CreateFormField(fieldname string) (io.Writer, error)
func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error)
func (w *Writer) FormDataContentType() string
func (w *Writer) Close() error
func NewReader(r io.Reader, boundary string) *Reader
func (r *Reader) NextPart() (*Part, error)
func (p *Part) FormName() string
func (p *Part) FileName() string

Write two parts with a fixed boundary, close the writer, then read both parts and close each one.

ParameterDescription
boundarySet before any part is created. The example uses TestBoundary so the text is deterministic. Production writers can keep the random default.
fieldname, filenameThe form name, and the file name for CreateFormFile. note.txt is sample data, not a path that is opened.

Returns: NextPart returns *Part and an error. After the last part, the error is io.EOF. Close on the Writer and on each Part returns an error if flushing fails.

Errors

  • io.EOF — Normal end of the part list after a well-formed, closed message.
  • error — SetBoundary fails if a part has already been written or if the boundary is invalid. NextPart fails on a truncated message, including one whose Writer was never closed.
  • The file part is written in memory. No local file is opened.
go
package main

import (
	"bytes"
	"fmt"
	"io"
	"mime"
	"mime/multipart"
)

func main() {
	var buf bytes.Buffer
	w := multipart.NewWriter(&buf)
	fmt.Println("boundary", w.SetBoundary("TestBoundary"))
	field, err := w.CreateFormField("title")
	fmt.Println("field", err)
	_, _ = field.Write([]byte("hello"))
	file, err := w.CreateFormFile("file", "note.txt")
	fmt.Println("file", err)
	_, _ = file.Write([]byte("abc"))
	fmt.Println("close_writer", w.Close())

	_, params, err := mime.ParseMediaType(w.FormDataContentType())
	fmt.Println("parsed_boundary", err, params["boundary"])

	r := multipart.NewReader(&buf, w.Boundary())
	for {
		part, err := r.NextPart()
		if err == io.EOF {
			fmt.Println("eof")
			break
		}
		fmt.Println("next", err)
		data, _ := io.ReadAll(part)
		fmt.Printf("name=%s file=%s data=%s\n", part.FormName(), part.FileName(), data)
		fmt.Println("close_part", part.Close())
	}
}

Expected output

boundary <nil>
field <nil>
file <nil>
close_writer <nil>
parsed_boundary <nil> TestBoundary
next <nil>
name=title file= data=hello
close_part <nil>
next <nil>
name=file file=note.txt data=abc
close_part <nil>
eof

Related: mime.ParseMediaType, io

Official documentation →

Limit a part as you read it

A part can be large even when the number of parts is small. This example reads only four bytes of a ten-byte field with io.LimitReader, then closes the part. The remaining bytes are discarded when the part is closed; the point is the cap, not a second uncached read. For an entire incoming request, prefer http.MaxBytesReader or ParseMultipartForm’s maxMemory argument on the server page.

io.LimitReader on a multipart.Part

func (r *Reader) NextPart() (*Part, error)
func LimitReader(r Reader, n int64) Reader

Read at most four bytes from one in-memory part, then close the part.

ParameterDescription
nThe maximum number of bytes to take from the part in this read.

Returns: ReadAll on the limited reader returns the prefix and a nil error when the cap is hit, because LimitReader then yields EOF.

  • Closing the part is still required after a limited read.
go
package main

import (
	"bytes"
	"fmt"
	"io"
	"mime/multipart"
)

func main() {
	var buf bytes.Buffer
	w := multipart.NewWriter(&buf)
	_ = w.SetBoundary("TestBoundary")
	field, _ := w.CreateFormField("blob")
	_, _ = field.Write([]byte("abcdefghij"))
	_ = w.Close()

	r := multipart.NewReader(&buf, "TestBoundary")
	part, err := r.NextPart()
	fmt.Println("next", err, part.FormName())
	data, err := io.ReadAll(io.LimitReader(part, 4))
	fmt.Println("limited", err, string(data))
	fmt.Println("close_part", part.Close())
}

Expected output

next <nil> blob
limited <nil> abcd
close_part <nil>

Related: net/http (server) MaxBytesReader, io.LimitReader

Official documentation →