File uploads
suggest changeBrowsers and HTTP clients upload files with a POST request whose body is encoded as multipart/form-data. Go supports it in the standard library:
mime/multipartencodes and decodes multipart bodiesnet/httphas helpers on*http.Request:ParseMultipartForm,FormFile,MultipartFormandMultipartReader
This article shows how to receive uploads on the server, how to limit and validate them, how to stream large files without buffering them, and how to upload files from a Go client. For other kinds of POST bodies see HTTP POST.
What a multipart body looks like
A multipart body is a list of parts separated by a boundary string. Each part has its own headers. A file part has a filename in its Content-Disposition header, and a regular form field doesn't.
We can see the exact bytes by encoding a body with multipart.Writer:
package main
import (
"bytes"
"fmt"
"log"
"mime/multipart"
)
func main() {
var body bytes.Buffer
mw := multipart.NewWriter(&body)
// a fixed boundary only to make the output stable; normally you
// let NewWriter pick a random one
if err := mw.SetBoundary("XyZ123"); err != nil {
log.Fatal(err)
}
mw.WriteField("title", "Holiday notes")
fw, err := mw.CreateFormFile("file", "notes.txt")
if err != nil {
log.Fatal(err)
}
fw.Write([]byte("Day 1: beach\nDay 2: mountains\n"))
// Close writes the final boundary
if err := mw.Close(); err != nil {
log.Fatal(err)
}
fmt.Println("Content-Type:", mw.FormDataContentType())
fmt.Println()
fmt.Print(body.String())
}
Content-Type: multipart/form-data; boundary=XyZ123
--XyZ123
Content-Disposition: form-data; name="title"
Holiday notes
--XyZ123
Content-Disposition: form-data; name="file"; filename="notes.txt"
Content-Type: application/octet-stream
Day 1: beach
Day 2: mountains
--XyZ123--
Things to know:
- the boundary is part of the
Content-Typeheader of the request. Always usemw.FormDataContentType()to set it, never a hand-written string. - you must call
mw.Close(). Without the closing--XyZ123--line the server reports anunexpected EOF. CreateFormFilealways sets the part'sContent-Typetoapplication/octet-stream. To send a different type, useCreatePart(shown later).- the separators are
\r\n, as HTTP requires.
An HTML upload form
On the browser side, the form must use method="post" and enctype="multipart/form-data". Without enctype the browser sends only the file name, not its content.
package main
import (
"fmt"
"log"
"net/http"
)
const page = `<!doctype html>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="files" multiple accept="image/*">
<button>Upload</button>
</form>`
func main() {
http.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, page)
})
http.HandleFunc("POST /upload", func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 20<<20)
if err := r.ParseMultipartForm(1 << 20); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for _, fh := range r.MultipartForm.File["files"] {
fmt.Fprintf(w, "%s: %d bytes\n", fh.Filename, fh.Size)
}
})
log.Fatal(http.ListenAndServe("localhost:8090", nil))
}
curl -F sends the same kind of request as the browser, which is handy for testing:
$ curl -F title=x -F files=@a.txt -F files=@b.txt http://localhost:8090/upload
a.txt: 3 bytes
b.txt: 6 bytes
accept="image/*" only filters the browser's file picker. Anyone can send anything to your server, so all checks must happen on the server.
Receiving a file with FormFile
The simplest way to get an uploaded file is r.FormFile(name). It returns:
- a
multipart.File, which is anio.Reader,io.ReaderAtandio.Seeker - a
*multipart.FileHeaderwith the client'sFilename,Sizeand partHeader
The example below runs a test server with httptest, uploads a file to it and saves the file in an upload directory:
package main
import (
"bytes"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
)
var uploadDir *os.Root
func handleUpload(w http.ResponseWriter, r *http.Request) {
// parse the body; up to 32 MB of file data is kept in memory,
// anything larger goes to temporary files on disk
if err := r.ParseMultipartForm(32 << 20); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
title := r.FormValue("title")
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "missing file: "+err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// never trust the client's file name as a path
name := filepath.Base(header.Filename)
dst, err := uploadDir.Create(name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer dst.Close()
n, err := io.Copy(dst, file)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "saved %q (%d bytes, title %q, client type %q)\n",
name, n, title, header.Header.Get("Content-Type"))
}
func upload(url, path string) {
var body bytes.Buffer
mw := multipart.NewWriter(&body)
mw.WriteField("title", "Holiday notes")
f, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
defer f.Close()
fw, err := mw.CreateFormFile("file", filepath.Base(path))
if err != nil {
log.Fatal(err)
}
if _, err := io.Copy(fw, f); err != nil {
log.Fatal(err)
}
mw.Close()
resp, err := http.Post(url, mw.FormDataContentType(), &body)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
msg, _ := io.ReadAll(resp.Body)
fmt.Printf("%s %s", resp.Status, msg)
}
func main() {
dir, _ := os.MkdirTemp("", "uploads")
defer os.RemoveAll(dir)
var err error
uploadDir, err = os.OpenRoot(dir)
if err != nil {
log.Fatal(err)
}
defer uploadDir.Close()
mux := http.NewServeMux()
mux.HandleFunc("POST /upload", handleUpload)
srv := httptest.NewServer(mux)
defer srv.Close()
// create a file to upload
src := filepath.Join(os.TempDir(), "notes.txt")
os.WriteFile(src, []byte("Day 1: beach\nDay 2: mountains\n"), 0o644)
defer os.Remove(src)
upload(srv.URL+"/upload", src)
data, _ := uploadDir.ReadFile("notes.txt")
fmt.Printf("on disk: %q\n", data)
}
200 OK saved "notes.txt" (30 bytes, title "Holiday notes", client type "application/octet-stream")
on disk: "Day 1: beach\nDay 2: mountains\n"
How it works:
ParseMultipartForm(maxMemory)reads the whole body. Up tomaxMemorybytes of file data are kept in memory, the rest is written to temporary files. Text fields are always kept in memory (up to an extra 10 MB).FormFileandFormValuecallParseMultipartForm(32 << 20)themselves if you didn't, so the explicit call is only needed when you want a differentmaxMemory.FormFilereturnshttp.ErrMissingFilewhen there's no file with that field name.- regular fields are available with
r.FormValue("title")orr.MultipartForm.Value. - after the handler returns,
net/httpdeletes the temporary files. If you callmultipart.Reader.ReadFormyourself, callform.RemoveAll()when done. - saving through an
os.Rootconfines all file operations to the upload directory, even if a crafted name slips through. See Application security for more aboutos.Rootand path traversal.
Limiting upload size
maxMemory is not a limit on the upload size. It only decides what goes to memory and what goes to disk. Without a limit, a client can fill your disk with one request.
Wrap the body with http.MaxBytesReader before parsing. Reading past the limit returns an *http.MaxBytesError, which you can check with errors.As:
package main
import (
"bytes"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
)
const maxUploadSize = 1 << 20 // 1 MB
func handleUpload(w http.ResponseWriter, r *http.Request) {
// reading more than maxUploadSize bytes of body returns an error
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
if err := r.ParseMultipartForm(256 << 10); err != nil {
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
msg := fmt.Sprintf("file too large (limit is %d bytes)", maxErr.Limit)
http.Error(w, msg, http.StatusRequestEntityTooLarge)
return
}
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
_, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "accepted %s: %d bytes\n", header.Filename, header.Size)
}
func upload(url string, size int) {
var body bytes.Buffer
mw := multipart.NewWriter(&body)
fw, _ := mw.CreateFormFile("file", fmt.Sprintf("data-%d.bin", size))
fw.Write(make([]byte, size))
mw.Close()
resp, err := http.Post(url, mw.FormDataContentType(), &body)
if err != nil {
fmt.Println("error:", err)
return
}
defer resp.Body.Close()
msg, _ := io.ReadAll(resp.Body)
fmt.Printf("%d bytes -> %s: %s", size, resp.Status, msg)
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(handleUpload))
defer srv.Close()
upload(srv.URL, 500_000)
upload(srv.URL, 2_000_000)
}
500000 bytes -> 200 OK: accepted data-500000.bin: 500000 bytes
2000000 bytes -> 413 Request Entity Too Large: file too large (limit is 1048576 bytes)
Notes:
- the limit applies to the whole body, including other fields and multipart headers, so leave some room above the largest file you accept.
MaxBytesReaderalso tells the server to close the connection after the response, so a client can't keep sending data.- a client that is still sending when the server rejects the request may get a "connection reset" error instead of the 413 response. That's normal; browsers usually show the response.
mime/multipartalso has its own limits against malicious input: at most 1000 parts per form and 10000 part headers. They can be changed withGODEBUG=multipartmaxparts=NandGODEBUG=multipartmaxheaders=N.- also set
ReadTimeoutorReadHeaderTimeouton yourhttp.Serverso that a slow client can't hold a connection open forever. For big uploads, a per-handler deadline withhttp.NewResponseController(w).SetReadDeadlineis better than a short globalReadTimeout.
Multiple files
<input type="file" multiple> sends every file as a separate part with the same field name. FormFile returns only the first one, so iterate r.MultipartForm.File[name] instead:
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"strings"
)
func handleUpload(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
// keep at most 64 KB in memory, spill the rest to temp files
if err := r.ParseMultipartForm(64 << 10); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "tags: %v\n", r.MultipartForm.Value["tag"])
for _, fh := range r.MultipartForm.File["files"] {
f, err := fh.Open()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
h := sha256.New()
io.Copy(h, f)
f.Close()
where := "memory"
if _, onDisk := f.(*os.File); onDisk {
where = "temp file"
}
fmt.Fprintf(w, "%-10s %7d bytes %-9s sha256 %x\n",
fh.Filename, fh.Size, where, h.Sum(nil)[:6])
}
// net/http deletes the temp files after the handler returns
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(handleUpload))
defer srv.Close()
var body bytes.Buffer
mw := multipart.NewWriter(&body)
mw.WriteField("tag", "photos")
mw.WriteField("tag", "2026")
files := map[string]string{
"a.txt": "small file",
"b.txt": strings.Repeat("x", 200_000),
"c.txt": "",
}
for _, name := range []string{"a.txt", "b.txt", "c.txt"} {
// same field name for all files, like <input type="file" multiple>
fw, _ := mw.CreateFormFile("files", name)
io.WriteString(fw, files[name])
}
mw.Close()
resp, err := http.Post(srv.URL, mw.FormDataContentType(), &body)
if err != nil {
panic(err)
}
defer resp.Body.Close()
io.Copy(os.Stdout, resp.Body)
}
tags: [photos 2026]
a.txt 10 bytes memory sha256 fadd1986cc26
b.txt 200000 bytes temp file sha256 91e3faafd322
c.txt 0 bytes memory sha256 e3b0c44298fc
The 200 KB file didn't fit in the 64 KB memory budget, so it was stored in a temporary file. Your code doesn't need to care: fh.Open() returns a multipart.File either way. An empty file is still a valid part with Size 0, so check for it if empty files make no sense in your application.
Streaming uploads with MultipartReader
ParseMultipartForm reads the entire body before your handler sees any of it. For large files that means writing everything to a temporary file and then copying it again to its final place.
r.MultipartReader() gives you the parts one at a time, as they arrive. You read each part directly from the network, with no temporary files and no memory buffering. The trade-off is that parts come in the order the client sent them, and you can't go back.
This handler streams each file to disk, computes its SHA-256 on the way, enforces a per-file size limit and names the file after its hash:
package main
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"strings"
)
const maxFileSize = 100_000
var uploadDir *os.Root
var errTooLarge = errors.New("file too large")
// saveStream copies at most limit bytes from src to a new file and returns
// its size and SHA-256. The file is named after its hash, so the client
// never chooses a path.
func saveStream(src io.Reader, limit int64) (int64, string, error) {
// random temporary name so concurrent uploads don't collide
tmpName := rand.Text() + ".tmp"
tmp, err := uploadDir.Create(tmpName)
if err != nil {
return 0, "", err
}
h := sha256.New()
// read one byte more than the limit to detect files that are too big
n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(src, limit+1))
tmp.Close()
if err == nil && n > limit {
err = errTooLarge
}
if err != nil {
uploadDir.Remove(tmpName)
return 0, "", err
}
sum := hex.EncodeToString(h.Sum(nil))
return n, sum, uploadDir.Rename(tmpName, sum)
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 10<<20)
mr, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// don't write to w until all parts are processed, so that we can
// still send an error status
var out strings.Builder
for {
part, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if part.FileName() == "" {
// a regular form field
v, _ := io.ReadAll(io.LimitReader(part, 1024))
fmt.Fprintf(&out, "field %s = %q\n", part.FormName(), v)
continue
}
n, sum, err := saveStream(part, maxFileSize)
if errors.Is(err, errTooLarge) {
http.Error(w, part.FileName()+": too large", http.StatusRequestEntityTooLarge)
return
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(&out, "file %s: %d bytes, stored as %s...\n", part.FileName(), n, sum[:12])
}
io.WriteString(w, out.String())
}
func post(url string, files map[string]string) {
var body bytes.Buffer
mw := multipart.NewWriter(&body)
mw.WriteField("album", "summer")
for name, content := range files {
fw, _ := mw.CreateFormFile("file", name)
io.WriteString(fw, content)
}
mw.Close()
resp, err := http.Post(url, mw.FormDataContentType(), &body)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
io.Copy(os.Stdout, resp.Body)
}
func main() {
dir, _ := os.MkdirTemp("", "uploads")
defer os.RemoveAll(dir)
uploadDir, _ = os.OpenRoot(dir)
defer uploadDir.Close()
srv := httptest.NewServer(http.HandlerFunc(handleUpload))
defer srv.Close()
post(srv.URL, map[string]string{"photo.jpg": strings.Repeat("j", 80_000)})
post(srv.URL, map[string]string{"video.mp4": strings.Repeat("v", 150_000)})
entries, _ := os.ReadDir(dir)
fmt.Println("files on disk:", len(entries))
}
200 OK
field album = "summer"
file photo.jpg: 80000 bytes, stored as 1b1de026d963...
413 Request Entity Too Large
video.mp4: too large
files on disk: 1
Details worth noting:
r.MultipartReader()fails if the body was already parsed, so don't callFormValueorParseMultipartFormbefore it.part.FormName()is the field name andpart.FileName()the client's file name (empty for regular fields).- you don't have to read a part to the end.
NextPartskips whatever is left of the previous part. - the rejected file was removed, so only one file is on disk. When a handler stores files as it goes, also think about cleaning up files saved from earlier parts of a request that fails later.
- the response is built in a
strings.Builderbecause once you write tow, the status code is sent and you can no longer reply with an error. Writing a 413 after writing the body produces asuperfluous response.WriteHeader callwarning in the log. - naming files by content hash deduplicates identical uploads for free.
rand.Text()(Go 1.24+) returns a random string that is safe to use in a file name.
Validating the content
The file name extension and the part's Content-Type header are both chosen by the client and prove nothing. To check what a file really is, look at its content. http.DetectContentType sniffs the first 512 bytes using the algorithm browsers use:
package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/textproto"
"os"
)
var allowedTypes = map[string]string{
"image/png": ".png",
"image/jpeg": ".jpg",
"application/pdf": ".pdf",
}
func handleUpload(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 5<<20)
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
// sniff the real type from the first 512 bytes
buf := make([]byte, 512)
n, err := io.ReadFull(file, buf)
if err != nil && err != io.ErrUnexpectedEOF {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
detected := http.DetectContentType(buf[:n])
ext, ok := allowedTypes[detected]
if !ok {
msg := fmt.Sprintf("%s: type %s not allowed (client said %s)",
header.Filename, detected, header.Header.Get("Content-Type"))
http.Error(w, msg, http.StatusUnsupportedMediaType)
return
}
// multipart.File is an io.Seeker: rewind before saving the whole file
if _, err := file.Seek(0, io.SeekStart); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// ... save file under a server-generated name with extension ext ...
fmt.Fprintf(w, "%s: ok, %s, will be saved with extension %s\n",
header.Filename, detected, ext)
}
func upload(url, name, contentType string, data []byte) {
var body bytes.Buffer
mw := multipart.NewWriter(&body)
// CreatePart lets us set the part's Content-Type header
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", multipart.FileContentDisposition("file", name))
h.Set("Content-Type", contentType)
pw, _ := mw.CreatePart(h)
pw.Write(data)
mw.Close()
resp, err := http.Post(url, mw.FormDataContentType(), &body)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Print(resp.StatusCode, " ")
io.Copy(os.Stdout, resp.Body)
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(handleUpload))
defer srv.Close()
png := []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR")
pdf := []byte("%PDF-1.7\n1 0 obj\n")
html := []byte("<html><script>alert(1)</script></html>")
upload(srv.URL, "cat.png", "image/png", png)
upload(srv.URL, "report.pdf", "application/pdf", pdf)
upload(srv.URL, "innocent.png", "image/png", html)
}
200 cat.png: ok, image/png, will be saved with extension .png
200 report.pdf: ok, application/pdf, will be saved with extension .pdf
415 innocent.png: type text/html; charset=utf-8 not allowed (client said image/png)
The client claimed innocent.png was a PNG, but it's an HTML page with a script. If you saved it as uploaded and later served it from your domain, a browser might run the script (stored XSS).
Rules for content checks:
- use an allowlist of types, never a denylist
- pick the stored file's extension from the detected type, not from the client's name
- magic bytes are a first filter, not proof. A file can start like a PNG and still be malformed. For images, decoding them (see Images) and re-encoding is the strongest check, and it also strips metadata such as GPS location.
- when serving user files back, set
Content-Typeyourself, addX-Content-Type-Options: nosniff, and useContent-Disposition: attachmentfor anything that shouldn't be shown inline. Serving uploads from a separate domain is even safer. multipart.FileContentDisposition(Go 1.25+) builds a correctly escapedContent-Dispositionvalue forCreatePart. On older versions, copy the escaping fromCreateFormFile.
Safe file names
part.FileName() and FileHeader.Filename already pass the name through filepath.Base, so ../../etc/passwd becomes passwd. But filepath.Base is platform dependent: on Linux it doesn't treat \ as a separator, so a Windows-style path survives. The name can also contain characters that are invalid on some file systems or confusing in HTML.
The safest approach is to not use the client's name for storage at all: generate a name (a random string or a content hash, as above) and keep the original name in a database for display. If you do want to keep a readable name, clean it:
package main
import (
"fmt"
"strings"
"unicode"
)
// safeName turns a client-supplied file name into something that's
// safe to show and to use as a single path component.
func safeName(name string) string {
// browsers on Windows used to send full paths like C:\Users\me\a.txt;
// strip directories using both separators, regardless of server OS
if i := strings.LastIndexAny(name, `/\`); i >= 0 {
name = name[i+1:]
}
name = strings.Map(func(r rune) rune {
switch {
case unicode.IsLetter(r), unicode.IsDigit(r), r == '.', r == '-', r == '_':
return r
case r == ' ':
return '_'
}
return -1 // drop everything else
}, name)
name = strings.TrimLeft(name, ".") // no hidden files, no ".."
if name == "" {
name = "unnamed"
}
return name
}
func main() {
names := []string{
"report.pdf",
"../../etc/passwd",
`C:\Users\me\My Photo.jpg`,
"..",
".htaccess",
"inv<o>ice?.pdf",
"zdjęcie łódź.png",
"a\x00b.txt",
"",
}
for _, n := range names {
fmt.Printf("%-28q -> %q\n", n, safeName(n))
}
}
"report.pdf" -> "report.pdf"
"../../etc/passwd" -> "passwd"
"C:\\Users\\me\\My Photo.jpg" -> "My_Photo.jpg"
".." -> "unnamed"
".htaccess" -> "htaccess"
"inv<o>ice?.pdf" -> "invoice.pdf"
"zdjęcie łódź.png" -> "zdjęcie_łódź.png"
"a\x00b.txt" -> "ab.txt"
"" -> "unnamed"
Even with a clean name, two users can upload report.pdf. os.Root.Create would silently overwrite the first one, so open with root.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) and pick another name if it fails with fs.ErrExist. Also limit the length; most file systems allow at most 255 bytes per name.
Uploading from a Go client without buffering
The client examples so far build the whole body in a bytes.Buffer, which is fine for small files. For a large file, connect multipart.Writer to the request body with io.Pipe. One goroutine writes the multipart data into the pipe while the HTTP client reads from it and sends it:
package main
import (
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
)
// uploadFile streams a file to url without loading it into memory.
func uploadFile(url, field, path string) (*http.Response, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
pr, pw := io.Pipe()
mw := multipart.NewWriter(pw)
// the writer side runs in its own goroutine; the HTTP client
// reads from pr as it sends the request
go func() {
// the goroutine owns f: Do can return before the body is fully
// written, e.g. when the server rejects the upload early
defer f.Close()
fw, err := mw.CreateFormFile(field, filepath.Base(path))
if err == nil {
_, err = io.Copy(fw, f)
}
if err == nil {
err = mw.Close()
}
// CloseWithError(nil) is the same as Close
pw.CloseWithError(err)
}()
req, err := http.NewRequest("POST", url, pr)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", mw.FormDataContentType())
return http.DefaultClient.Do(req)
}
func main() {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mr, err := r.MultipartReader()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
part, err := mr.NextPart()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
n, err := io.Copy(io.Discard, part)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "received %s: %d bytes (Content-Length %d, %v)\n",
part.FileName(), n, r.ContentLength, r.TransferEncoding)
}))
defer srv.Close()
// create a 50 MB file
path := filepath.Join(os.TempDir(), "big.bin")
f, _ := os.Create(path)
f.Truncate(50 << 20)
f.Close()
defer os.Remove(path)
resp, err := uploadFile(srv.URL, "file", path)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
io.Copy(os.Stdout, resp.Body)
}
received big.bin: 52428800 bytes (Content-Length -1, [chunked])
Memory use stays small no matter how big the file is. Points to watch:
- the file is closed by the goroutine, not by
uploadFile. If the server responds before reading the whole body,Doreturns early, the transport closes the pipe reader and the goroutine's next write fails withio.ErrClosedPipe, ending it. - always close the pipe writer, with
CloseWithError(err)on failure. Otherwise the request hangs forever, or the server receives a truncated body that looks complete. - since the length isn't known in advance, the request is sent with chunked transfer encoding (
Content-Length -1). A few servers and proxies (some S3-style APIs among them) require aContent-Length. If so, compute it up front: the multipart overhead is fixed for a given boundary, soreq.ContentLength = overhead + fileSizeworks. - to show a progress bar, wrap
fin a reader that counts bytes asio.Copyreads them. - use a context with a timeout via
http.NewRequestWithContextso a stuck upload can be cancelled.
Testing upload handlers
You don't need a running server to test a handler. Build the request body with multipart.Writer, create a request with httptest.NewRequest and record the response with httptest.NewRecorder:
package upload
import (
"fmt"
"io"
"net/http"
)
func HandleUpload(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
file, header, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer file.Close()
n, err := io.Copy(io.Discard, file)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "%s %d", header.Filename, n)
}
package upload
import (
"bytes"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// newUploadRequest builds a multipart POST request with one file.
func newUploadRequest(t *testing.T, field, name string, content []byte) *http.Request {
t.Helper()
var body bytes.Buffer
mw := multipart.NewWriter(&body)
fw, err := mw.CreateFormFile(field, name)
if err != nil {
t.Fatal(err)
}
fw.Write(content)
if err := mw.Close(); err != nil {
t.Fatal(err)
}
req := httptest.NewRequest("POST", "/upload", &body)
req.Header.Set("Content-Type", mw.FormDataContentType())
return req
}
func TestHandleUpload(t *testing.T) {
tests := []struct {
name string
field string
size int
wantStatus int
wantBody string
}{
{"ok", "file", 1000, http.StatusOK, "a.txt 1000"},
{"wrong field", "document", 10, http.StatusBadRequest, "no such file"},
{"too large", "file", 2 << 20, http.StatusBadRequest, "too large"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
req := newUploadRequest(t, tc.field, "a.txt", make([]byte, tc.size))
rec := httptest.NewRecorder()
HandleUpload(rec, req)
if rec.Code != tc.wantStatus {
t.Errorf("status = %d, want %d", rec.Code, tc.wantStatus)
}
if got := rec.Body.String(); !strings.Contains(got, tc.wantBody) {
t.Errorf("body = %q, want it to contain %q", got, tc.wantBody)
}
})
}
}
$ go test -v
=== RUN TestHandleUpload
=== RUN TestHandleUpload/ok
=== RUN TestHandleUpload/wrong_field
=== RUN TestHandleUpload/too_large
--- PASS: TestHandleUpload (0.00s)
--- PASS: TestHandleUpload/ok (0.00s)
--- PASS: TestHandleUpload/wrong_field (0.00s)
--- PASS: TestHandleUpload/too_large (0.00s)
PASS
The test cases use table-driven tests to cover the success path, a missing file and an oversized body. Forgetting to set the Content-Type header with the boundary is the most common reason such tests fail with request Content-Type isn't multipart/form-data.
Common mistakes
- No size limit.
maxMemoryonly controls buffering. Always wrapr.Bodywithhttp.MaxBytesReader. - Trusting the file name. Never join it into a path. Generate storage names and use
os.Root. - Trusting the content type. Check the bytes with
http.DetectContentTypeagainst an allowlist, or decode the file. - Forgetting
enctype="multipart/form-data"in the HTML form.FormFilethen fails withrequest Content-Type isn't multipart/form-data. - Forgetting
mw.Close()on the client. The server sees an incomplete body and fails withunexpected EOF. - Mixing
FormValueandMultipartReader. CallingFormValueparses the whole body;MultipartReaderthen fails withhttp: multipart handled by ParseMultipartForm. - Serving uploads inline from your main domain. Uploaded HTML or SVG can run scripts. Use
Content-Disposition: attachment,nosniff, or a separate domain.
Summary
- uploads are
POSTrequests with amultipart/form-databody; the boundary is in theContent-Typeheader r.FormFile(name)is the easiest way to get one file;r.MultipartForm.File[name]gives all files for a fieldParseMultipartForm(maxMemory)buffers up tomaxMemoryin memory and the rest in temporary files thatnet/httpremoves after the handler- limit the request size with
http.MaxBytesReaderand check for*http.MaxBytesError r.MultipartReader()streams parts without temporary files; use it for large uploads- validate content with
http.DetectContentTypeand an allowlist, and store files under names you generate - on the client, use
multipart.Writer, setFormDataContentType(), callClose(), and useio.Pipeto stream big files