liveBook · Manning

FormFile

As explained in Go in Practice, Second Edition

FormFile is a Go HTTP request method that returns an uploaded file, its metadata header, and an error if retrieval fails.

FormFile retrieves one uploaded file from a multipart HTTP request. It returns a file object, a metadata header containing information such as the filename, and an error when retrieval fails. section 10.2.3

Use FormFile when processing a form with one file per input field:

  • Accept a POST form encoded as multipart/form-data. section 10.2.3
  • Call r.FormFile("file") to obtain f, h, and err. section 10.2.3
  • Use h.Filename when constructing the destination name, while treating the upload as binary data surrounded by metadata. section 10.2.3

Saving one uploaded file

func fileForm(w http.ResponseWriter, r *http.Request) { f, h, err := r.FormFile("file") if err != nil { panic(err) } defer f.Close() out, err := os.Create("/tmp/" + h.Filename) if err != nil { panic(err) } defer out.Close() io.Copy(out, f) fmt.Fprint(w, "Upload complete") }

How Go in Practice, Second Edition covers it

How deep it goes
Explains returned values, error handling, closing resources, naming output, and copying bytes, but stops short of multi-file processing.
Examples
Uses a multipart HTML upload form and a Go handler that saves one uploaded file under its submitted filename.
What it assumes
Assumes basic Go HTTP handlers and form submissions while clarifying multipart encoding and binary-file metadata.
What you can do after
Apply it via Go's HTTP server to retrieve, close, and save a single uploaded file.
How it connects
Connects multipart forms with Request, multipart.FileHeader, ParseMultipartForm, and binary file handling.

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.