liveBook · Manning

ParseMultipartForm

As explained in Go in Practice, Second Edition

ParseMultipartForm is a Go HTTP request method that parses multipart form data and makes its parts available through the request's form fields and file APIs.

An HTTP request containing form data is not parsed into usable fields by default. In a Go handler, call r.ParseMultipartForm(maxMemory) when a multipart submission contains files or when you need direct access to its parsed parts. Unlike ParseForm, which handles text fields, this method makes file fields available too. section 10.2.1 section 10.2.4

The maxMemory argument sets how much memory is used for file parts; parts exceeding it are stored in temporary files on disk. For example, 16 << 20 specifies 16 MB. FormValue and PostFormValue can trigger multipart parsing automatically, using a default of 32 MB; FormFile also handles parsing internally. Call ParseMultipartForm explicitly when you want to choose the memory threshold or inspect MultipartForm. section 10.2.2 section 10.2.4

Choose the field API according to what you need:

  • For every submitted text value under one name, iterate r.PostForm["names"]. PostForm excludes URL query values; Form includes them. section 10.2.1 section 10.2.2
  • For one uploaded file, use r.FormFile("file") to obtain the file and its metadata. section 10.2.3
  • For multiple uploads under one field, iterate r.MultipartForm.File["files"]. Each *multipart.FileHeader can be opened to read and save that file. section 10.2.4

Read repeated multipart text values

In an http.Handler, check the parsing error before using the fields: if err := r.ParseMultipartForm(16 << 20); err != nil { fmt.Fprint(w, err) return } for _, name := range r.PostForm["names"] { fmt.Println(name) } Indexing PostForm retains all submitted values rather than only the first value returned by PostFormValue. section 10.2.2

For many large or concurrent uploads, temporary files can demand substantial disk space. If files should be processed as they arrive instead, use r.MultipartReader() and read the incoming parts incrementally rather than calling ParseMultipartForm. section 10.2.6

How Go in Practice, Second Edition covers it

How deep it goes
Shows memory thresholds, parsed field access, and file handling; defers incremental processing to MultipartReader.
Examples
Uses repeated text fields, a single-file upload form, and a multiple-file upload handler.
What it assumes
Assumes basic HTTP handlers and HTML forms; explains the distinction between text-form and multipart parsing.
What you can do after
Apply it via Go net/http to parse multipart forms, choose a memory threshold, and access uploaded files.
How it connects
Connects ParseForm, FormValue, PostForm, FormFile, MultipartForm, and MultipartReader.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.