liveBook · Manning

Multipart.FileHeader

As explained in Go in Practice, Second Edition

multipart.FileHeader is a Go structure containing metadata about an uploaded multipart file and providing access to its contents.

multipart.FileHeader is a pointer-backed Go structure that represents one uploaded multipart file. It exposes uploaded metadata and provides Open, which returns a file handler for reading the contents. section 10.2.4

Use a FileHeader when processing one or more uploaded files:

  • Call ParseMultipartForm before reading multipart fields; its memory limit controls how much form data stays in memory, with remaining files written to temporary disk storage. section 10.2.4
  • Retrieve multiple uploads from Request.MultipartForm.File, where each entry is a *multipart.FileHeader. section 10.2.4
  • Call Open to read a header's contents, use Filename for a local destination name, and copy the data with io.Copy. section 10.2.4
  • Inspect Header["Content-Type"] when assessing the uploader-provided MIME type, while recognizing that the value may be generic or untrusted. section 10.2.5

Process several uploaded files

After parsing the request, iterate over r.MultipartForm.File["files"]. For each header, call fh.Open(), create a destination file, and copy the uploaded contents. The multiple-value input field is named files and uses multipart/form-data. section 10.2.4

file, header, err := r.FormFile("file")
contentType := header.Header["Content-Type"][0]

Inspect the uploaded Content-Type through the FileHeader Header field after calling Request.FormFile. section 10.2.5

file, header, err := r.FormFile("file")
extension := filepath.Ext(header.Filename)
type := mime.TypeByExtension(extension)

Derive a tentative MIME type from FileHeader.Filename with filepath.Ext and mime.TypeByExtension. section 10.2.5

file, header, err := r.FormFile("file")
buffer := make([]byte, 512)
_, err = file.Read(buffer)
filetype := http.DetectContentType(buffer)

Read file bytes returned by FormFile and use http.DetectContentType to infer type from contents. section 10.2.5

How Go in Practice, Second Edition covers it

How deep it goes
Explains retrieval, opening, saving, and MIME inspection, but stops short of a complete security-validation policy.
Examples
Uses a multiple-file form, sequential header processing, local file creation, and three MIME-type inspection strategies.
What it assumes
Assumes basic Go HTTP request handling and multipart forms while demonstrating parsing and file processing.
What you can do after
Apply it via Go's multipart APIs to open, store, and inspect uploaded files.
How it connects
Links multipart forms with Request.FormFile, MIME types, filepath.Ext, mime.TypeByExtension, http.DetectContentType, and io.Copy.

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.