ZetCode

Go file upload

last modified November 19, 2026 Go 1.27

In this article we show how to upload files to a Go web server. We look at the multipart format, read and save uploaded files, accept several files with form fields, limit the upload size, check the real file type, stream large uploads and send files from a Go client.

All examples in this article were run with Go 1.27.0 and curl 7.81 on Linux. The servers listen on 127.0.0.1:8080; we start each one in one terminal and send requests from another. The test files are notes.txt, a 53-byte line of text, gopher.png, a small PNG image, and big.bin, 3 MB of random data created with head -c 3000000 /dev/urandom > big.bin.

Multipart form data

A browser uploads files with an HTML form whose encoding is multipart/form-data. The request body then consists of parts, one for each form field, separated by a boundary string. The format is defined in RFC 7578. The first server prints the raw body, so we can see the format.

dump_body.go
package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
)

func dump(w http.ResponseWriter, r *http.Request) {

    fmt.Println("Content-Type:", r.Header.Get("Content-Type"))
    fmt.Println()

    if _, err := io.Copy(os.Stdout, r.Body); err != nil {
        log.Println(err)
    }
}

func main() {

    http.HandleFunc("POST /upload", dump)
    log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

The handler prints the Content-Type header of the request and copies the body to the standard output.

if _, err := io.Copy(os.Stdout, r.Body); err != nil {

The request body is an io.Reader, so it can be copied without reading it into memory.

We send a file and a text field with curl -F "file=@notes.txt" -F "title=My notes" http://127.0.0.1:8080/upload. The -F option of curl builds a multipart request, and @ means that the value is the content of a file. The output shows the server terminal. The boundary is chosen by the client and given in the Content-Type header. Each part has its own headers: Content-Disposition holds the field name and, for files, the file name. The last boundary ends with --.

$ go run dump_body.go
Content-Type: multipart/form-data; boundary=------------------------7dcf56a356fbfb3a

--------------------------7dcf56a356fbfb3a
Content-Disposition: form-data; name="file"; filename="notes.txt"
Content-Type: text/plain

Go makes it easy to build simple, reliable software.

--------------------------7dcf56a356fbfb3a
Content-Disposition: form-data; name="title"

My notes
--------------------------7dcf56a356fbfb3a--

Reading an uploaded file

Parsing the parts by hand is not necessary. The FormFile method of the request returns the first file of a form field.

form_file.go
package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
)

func upload(w http.ResponseWriter, r *http.Request) {

    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.StatusInternalServerError)
        return
    }

    fmt.Fprintf(w, "received %s: %d bytes, %s\n",
        header.Filename, n, header.Header.Get("Content-Type"))
}

func main() {

    http.HandleFunc("POST /upload", upload)
    log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

The handler reads the uploaded file and reports its name, size and type.

file, header, err := r.FormFile("file")

FormFile parses the multipart body and returns the file content as a multipart.File and its metadata as a *multipart.FileHeader. If the form has no file under that name, it returns http.ErrMissingFile.

n, err := io.Copy(io.Discard, file)

The file is a reader; here we only count its bytes.

header.Filename, n, header.Header.Get("Content-Type"))

Filename is the name sent by the client, and Header holds the part headers. The content type comes from the client, too; curl guesses it from the file extension. The third request uses a wrong field name.

$ curl -F "file=@gopher.png" http://127.0.0.1:8080/upload
received gopher.png: 83 bytes, image/png
$ curl -F "file=@notes.txt" http://127.0.0.1:8080/upload
received notes.txt: 53 bytes, text/plain
$ curl -F "doc=@notes.txt" http://127.0.0.1:8080/upload
http: no such file

Saving the file

To keep an uploaded file, we copy it to a file in an upload directory. Everything the client sends, including the file name, must be treated as untrusted.

save_file.go
package main

import (
    "errors"
    "fmt"
    "io"
    "io/fs"
    "log"
    "net/http"
    "os"
    "path/filepath"
)

const uploadDir = "uploads"

func upload(w http.ResponseWriter, r *http.Request) {

    file, header, err := r.FormFile("file")
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    defer file.Close()

    path := filepath.Join(uploadDir, header.Filename)

    dst, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
    if errors.Is(err, fs.ErrExist) {
        http.Error(w, "file already exists", http.StatusConflict)
        return
    }
    if err != nil {
        http.Error(w, "cannot save file", http.StatusInternalServerError)
        return
    }
    defer dst.Close()

    n, err := io.Copy(dst, file)
    if err != nil {
        http.Error(w, "cannot save file", http.StatusInternalServerError)
        return
    }

    fmt.Fprintf(w, "saved %s (%d bytes)\n", path, n)
}

func main() {

    if err := os.MkdirAll(uploadDir, 0o755); err != nil {
        log.Fatal(err)
    }

    http.HandleFunc("POST /upload", upload)
    log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

The server creates the uploads directory at start and stores each file under its original name.

path := filepath.Join(uploadDir, header.Filename)

A malicious client can send a file name such as ../../.bashrc. Go removes the directory part from file names of multipart parts, so Filename never contains a slash. Applications that store many files usually generate their own names and keep the original one only for display.

dst, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
if errors.Is(err, fs.ErrExist) {

The O_EXCL flag makes OpenFile fail if the file exists, so an upload cannot overwrite an earlier one. The server answers 409 Conflict in that case.

n, err := io.Copy(dst, file)

io.Copy writes the upload to disk in chunks. The output shows three uploads; curl's filename= option sets the file name sent to the server.

$ curl -F "file=@notes.txt" http://127.0.0.1:8080/upload
saved uploads/notes.txt (53 bytes)
$ curl -F "file=@notes.txt" http://127.0.0.1:8080/upload
file already exists
$ curl -F "file=@notes.txt;filename=../../evil.txt" http://127.0.0.1:8080/upload
saved uploads/evil.txt (53 bytes)
$ ls uploads
evil.txt
notes.txt

Several files and form fields

An upload form often has text fields and lets the user select several files. The following page is served by the next server at /.

upload.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Upload files</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="text" name="title" placeholder="Title">
    <input type="file" name="files" multiple>
    <button type="submit">Upload</button>
</form>
</body>
</html>

The enctype attribute selects the multipart encoding; without it, the browser would send only the file names. The multiple attribute lets the user select several files, which are sent as several parts with the same name, files.

multi_files.go
package main

import (
    "fmt"
    "log"
    "net/http"
)

func form(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w, r, "upload.html")
}

func upload(w http.ResponseWriter, r *http.Request) {

    if err := r.ParseMultipartForm(10 << 20); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    title := r.FormValue("title")
    files := r.MultipartForm.File["files"]

    if len(files) == 0 {
        http.Error(w, "no files", http.StatusBadRequest)
        return
    }

    fmt.Fprintf(w, "title: %q, %d files\n", title, len(files))

    for _, fh := range files {
        fmt.Fprintf(w, "  %s: %d bytes, %s\n",
            fh.Filename, fh.Size, fh.Header.Get("Content-Type"))
    }
}

func main() {

    http.HandleFunc("GET /", form)
    http.HandleFunc("POST /upload", upload)

    log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

The handler parses the whole form first and then reads the text field and the list of files.

if err := r.ParseMultipartForm(10 << 20); err != nil {

ParseMultipartForm reads all parts. Up to the given number of bytes, here 10 MB, are kept in memory; larger files are stored in temporary files, which the server removes after the request. FormFile called this method for us with a limit of 32 MB.

title := r.FormValue("title")
files := r.MultipartForm.File["files"]

FormValue returns a text field. The files are in r.MultipartForm.File, a map from field names to lists of *multipart.FileHeader; each header has the size, and its Open method returns the content. The second command checks that the server returns the form.

$ curl -F "title=Holiday" -F "files=@gopher.png" -F "files=@notes.txt" http://127.0.0.1:8080/upload
title: "Holiday", 2 files
  gopher.png: 83 bytes, image/png
  notes.txt: 53 bytes, text/plain
$ curl -s http://127.0.0.1:8080/ | grep form
<form action="/upload" method="post" enctype="multipart/form-data">
</form>

Limiting the upload size

ParseMultipartForm limits the memory, not the size of the upload: a client can fill the disk with temporary files. The http.MaxBytesReader function limits how much of the body is read at all.

size_limit.go
package main

import (
    "errors"
    "fmt"
    "log"
    "net/http"
)

const maxUpload = 1 << 20

func upload(w http.ResponseWriter, r *http.Request) {

    r.Body = http.MaxBytesReader(w, r.Body, maxUpload)

    err := r.ParseMultipartForm(32 << 10)

    var tooLarge *http.MaxBytesError
    if errors.As(err, &tooLarge) {
        msg := fmt.Sprintf("upload larger than %d bytes", tooLarge.Limit)
        http.Error(w, msg, http.StatusRequestEntityTooLarge)
        return
    }
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    for _, fh := range r.MultipartForm.File["file"] {
        fmt.Fprintf(w, "accepted %s: %d bytes\n", fh.Filename, fh.Size)
    }
}

func main() {

    http.HandleFunc("POST /upload", upload)
    log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

The server accepts at most 1 MB per request.

r.Body = http.MaxBytesReader(w, r.Body, maxUpload)

The wrapped body returns an error once more than maxUpload bytes have been read. It also tells the server to close the connection after the response, so that the rest of the body does not have to be read.

var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {

The error is a *http.MaxBytesError, and the server answers 413 Request Entity Too Large. The -i option of curl prints the response headers. For large bodies, curl first asks with an Expect: 100-continue header whether to send the body; the Go server agrees with 100 Continue when the handler starts reading the body.

$ curl -F "file=@notes.txt" http://127.0.0.1:8080/upload
accepted notes.txt: 53 bytes
$ curl -i -F "file=@big.bin" http://127.0.0.1:8080/upload
HTTP/1.1 100 Continue

HTTP/1.1 413 Request Entity Too Large
Connection: close
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Thu, 19 Nov 2026 15:00:21 GMT
Content-Length: 33

upload larger than 1048576 bytes

Checking the file type

The file name and the content type are chosen by the client, so neither proves what the file contains. A server that accepts only images should look at the content itself.

detect_type.go
package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
)

var allowed = map[string]bool{
    "image/png":  true,
    "image/jpeg": true,
    "image/gif":  true,
}

func upload(w http.ResponseWriter, r *http.Request) {

    file, header, err := r.FormFile("image")
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    defer file.Close()

    head := make([]byte, 512)
    n, err := io.ReadFull(file, head)
    if err != nil && err != io.ErrUnexpectedEOF {
        http.Error(w, "cannot read file", http.StatusBadRequest)
        return
    }

    detected := http.DetectContentType(head[:n])
    claimed := header.Header.Get("Content-Type")

    if !allowed[detected] {
        msg := fmt.Sprintf("%s: claimed %s, detected %s", header.Filename, claimed, detected)
        http.Error(w, msg, http.StatusUnsupportedMediaType)
        return
    }

    if _, err := file.Seek(0, io.SeekStart); err != nil {
        http.Error(w, "cannot read file", http.StatusInternalServerError)
        return
    }

    fmt.Fprintf(w, "%s: %s image accepted\n", header.Filename, detected)
}

func main() {

    http.HandleFunc("POST /upload", upload)
    log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

The handler reads the start of the file and detects the type from it.

head := make([]byte, 512)
n, err := io.ReadFull(file, head)
if err != nil && err != io.ErrUnexpectedEOF {

io.ReadFull reads up to 512 bytes; for a smaller file it returns io.ErrUnexpectedEOF, which is fine here.

detected := http.DetectContentType(head[:n])

http.DetectContentType implements the content sniffing algorithm of browsers; it checks known signatures, such as the first bytes of PNG files, and considers at most 512 bytes.

if _, err := file.Seek(0, io.SeekStart); err != nil {

An uploaded file is also an io.Seeker. A server that saves the image goes back to the start before copying it.

For the test, setup.png holds the first 600 bytes of a Linux program, and the third request sends a text file with a forged content type. Both are rejected with 415 Unsupported Media Type.

$ curl -F "image=@gopher.png" http://127.0.0.1:8080/upload
gopher.png: image/png image accepted
$ curl -F "image=@setup.png" http://127.0.0.1:8080/upload
setup.png: claimed image/png, detected application/octet-stream
$ curl -F "image=@notes.txt;type=image/png" http://127.0.0.1:8080/upload
notes.txt: claimed image/png, detected text/plain; charset=utf-8

Streaming the parts

ParseMultipartForm reads the whole body before the handler can look at it. For large uploads, the MultipartReader method returns the parts one by one as they arrive, without temporary files.

stream_parts.go
package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
)

func upload(w http.ResponseWriter, r *http.Request) {

    r.Body = http.MaxBytesReader(w, r.Body, 100<<20)

    reader, err := r.MultipartReader()
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    for {
        part, err := reader.NextPart()
        if err == io.EOF {
            break
        }
        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
        }

        if part.FileName() == "" {
            fmt.Fprintf(w, "field %s: %d bytes\n", part.FormName(), n)
        } else {
            fmt.Fprintf(w, "file %s (%s): %d bytes\n", part.FormName(), part.FileName(), n)
        }
    }
}

func main() {

    http.HandleFunc("POST /upload", upload)
    log.Fatal(http.ListenAndServe("127.0.0.1:8080", nil))
}

The handler processes the body as a stream of parts.

reader, err := r.MultipartReader()

MultipartReader returns a *multipart.Reader. It fails if the request is not a multipart request. The body is still limited with MaxBytesReader, here to 100 MB.

part, err := reader.NextPart()
if err == io.EOF {
    break
}

NextPart returns the next part, and io.EOF after the last one. The data is read straight from the connection; unread data of the previous part is skipped.

if part.FileName() == "" {

Text fields have no file name. A real server would copy file parts to their destination, for example a file or cloud storage, instead of io.Discard.

$ curl -F "title=Backup" -F "data=@big.bin" -F "notes=@notes.txt" http://127.0.0.1:8080/upload
field title: 6 bytes
file data (big.bin): 3000000 bytes
file notes (notes.txt): 53 bytes

Uploading from Go

The mime/multipart package also writes multipart bodies. The client uploads two files and a text field to the server from the Several files and form fields section.

upload_client.go
package main

import (
    "bytes"
    "fmt"
    "io"
    "log"
    "mime/multipart"
    "net/http"
    "os"
)

func main() {

    var body bytes.Buffer
    mw := multipart.NewWriter(&body)

    if err := mw.WriteField("title", "From Go"); err != nil {
        log.Fatal(err)
    }

    for _, name := range []string{"notes.txt", "gopher.png"} {

        data, err := os.ReadFile(name)
        if err != nil {
            log.Fatal(err)
        }

        part, err := mw.CreateFormFile("files", name)
        if err != nil {
            log.Fatal(err)
        }

        if _, err := part.Write(data); err != nil {
            log.Fatal(err)
        }
    }

    if err := mw.Close(); err != nil {
        log.Fatal(err)
    }

    res, err := http.Post("http://127.0.0.1:8080/upload", mw.FormDataContentType(), &body)
    if err != nil {
        log.Fatal(err)
    }
    defer res.Body.Close()

    reply, err := io.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(res.Status)
    fmt.Print(string(reply))
}

The body is built in a buffer first and then sent.

mw := multipart.NewWriter(&body)

multipart.NewWriter writes parts to the buffer and chooses a random boundary.

part, err := mw.CreateFormFile("files", name)

CreateFormFile starts a file part and returns a writer for its content. It always sets the type application/octet-stream, as the output shows; CreatePart lets us set the part headers ourselves. WriteField adds a text field.

if err := mw.Close(); err != nil {

Close writes the final boundary. Without it, the server sees an incomplete body.

res, err := http.Post("http://127.0.0.1:8080/upload", mw.FormDataContentType(), &body)

FormDataContentType returns the Content-Type header with the boundary.

$ go run upload_client.go
200 OK
title: "From Go", 2 files
  notes.txt: 53 bytes, application/octet-stream
  gopher.png: 83 bytes, application/octet-stream

Streaming uploads

Building the body in a buffer keeps the whole file in memory. With io.Pipe, a goroutine writes the multipart body while the HTTP client sends it. This client uploads big.bin to the streaming server from the previous sections.

pipe_client.go
package main

import (
    "fmt"
    "io"
    "log"
    "mime/multipart"
    "net/http"
    "os"
)

func writeForm(mw *multipart.Writer, name string) error {

    f, err := os.Open(name)
    if err != nil {
        return err
    }
    defer f.Close()

    part, err := mw.CreateFormFile("data", name)
    if err != nil {
        return err
    }

    if _, err := io.Copy(part, f); err != nil {
        return err
    }

    return mw.Close()
}

func main() {

    pr, pw := io.Pipe()
    mw := multipart.NewWriter(pw)

    go func() {
        pw.CloseWithError(writeForm(mw, "big.bin"))
    }()

    res, err := http.Post("http://127.0.0.1:8080/upload", mw.FormDataContentType(), pr)
    if err != nil {
        log.Fatal(err)
    }
    defer res.Body.Close()

    reply, err := io.ReadAll(res.Body)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(res.Status)
    fmt.Print(string(reply))
}

The writeForm function copies the file into a part and closes the multipart writer.

pr, pw := io.Pipe()
mw := multipart.NewWriter(pw)

io.Pipe connects a writer and a reader: what the multipart writer writes into pw, the HTTP client reads from pr. The pipe article covers pipes in detail.

go func() {
    pw.CloseWithError(writeForm(mw, "big.bin"))
}()

The writing must run in a separate goroutine, because a pipe write blocks until the other side reads. CloseWithError ends the body. With a nil error, the reader sees a normal end; otherwise the request fails with the error. For example, with a missing file the client prints open missing.bin: no such file or directory.

$ go run pipe_client.go
200 OK
file data (big.bin): 3000000 bytes

Source

Go mime/multipart package - reference
Go http.Request.FormFile - reference
RFC 7578 - Returning Values from Forms: multipart/form-data

In this article we have uploaded files to a Go server: the multipart format, reading and saving files, several files with form fields, size limits, type checks, streaming on the server and uploads from a Go client. The HTTP server article covers handlers and HTML forms, the httptest article shows how to test handlers, and the GET/POST request article sends other kinds of request bodies.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.