Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Templates and Static Files

File Uploads and Downloads in Gin

Accept single and multiple file uploads in Gin with c.FormFile and c.MultipartForm, limit sizes, validate file types, store safely and send downloads with FileAttachment.

Profile pictures, CSV imports, PDF invoices: sooner or later your application has to accept files from users and hand files back. Uploads are also one of the riskiest features of any web app, because you let strangers put bytes on your server. This lesson shows Gin's upload helpers, then focuses on the checks that make them safe: size limits, type checks and trustworthy file names.

Gin itself cannot run in the in-page runner, so the Gin code is read-only. The runnable examples build real multipart requests with the standard library and handle them with net/http, which is what c.FormFile wraps.

How an upload travels

A browser sends a file in a multipart/form-data request body. Each field (text or file) is one part, separated by a boundary string. The form must say so:

HTML
<form method="post" action="/upload" enctype="multipart/form-data">
  <input type="file" name="avatar">
  <button>Upload</button>
</form>

Without enctype="multipart/form-data" the browser only sends the file's name, a classic beginner bug.

Single file

Go
r := gin.Default()
r.MaxMultipartMemory = 8 << 20 // 8 MiB kept in memory, the rest spills to temp files

r.POST("/upload", func(c *gin.Context) {
	file, err := c.FormFile("avatar")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "avatar is required"})
		return
	}
	dst := filepath.Join("uploads", uuid.NewString()+filepath.Ext(file.Filename))
	if err := c.SaveUploadedFile(file, dst); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "could not save"})
		return
	}
	c.JSON(http.StatusCreated, gin.H{"size": file.Size, "saved": dst})
})

c.FormFile returns a *multipart.FileHeader with Filename, Size and a Header map. c.SaveUploadedFile copies it to disk. Two important details: MaxMultipartMemory is not a size limit, it only controls how much stays in RAM before spilling to disk; and the Filename comes from the client, so it can lie.

Multiple files

Go
r.POST("/gallery", func(c *gin.Context) {
	form, err := c.MultipartForm()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	files := form.File["photos"] // <input type="file" name="photos" multiple>
	for _, f := range files {
		c.SaveUploadedFile(f, "uploads/"+uuid.NewString()+filepath.Ext(f.Filename))
	}
	c.JSON(http.StatusOK, gin.H{"count": len(files), "title": form.Value["title"]})
})

form.File maps field names to lists of files, and form.Value holds the ordinary text fields that came along.

See a multipart request being built and read

The stand-in below constructs the exact body a browser would send, parses it, and reads the file back. Nothing here touches the disk.

Go Build and parse a multipart upload

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Rule 1: limit the size

A client can send a 10 GB body. Cap it before parsing. In plain net/http that is http.MaxBytesReader; in Gin you call the same function on the request body, in a middleware or at the top of the handler:

Go
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 5<<20) // 5 MiB
file, err := c.FormFile("avatar")
if err != nil { // too large also shows up here
	c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file too large (max 5 MiB)"})
	return
}

Also set a limit at the reverse proxy (client_max_body_size in nginx), so oversized bodies never reach Go.

Rule 2: never trust the name or the declared type

The client controls Filename (it might be ../../etc/cron.d/evil or shell.php) and the Content-Type of each part. So:

  • Generate your own file name (a UUID or a hash) and keep only a vetted extension.
  • At most use filepath.Base on the original name for display, never for the path on disk.
  • Sniff the content with http.DetectContentType, which inspects the first 512 bytes and returns the real type.
  • Keep uploaded files outside any folder you serve with Static, or at least never execute them.
Go Check size and real content type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second call shows why sniffing matters: a script renamed to avatar.png is detected as text and rejected.

Rule 3: store with your own name

Combine the previous ideas. The following handler stand-in saves into an in-memory map and answers with the generated name; in a real app you would call c.SaveUploadedFile and keep the metadata (owner, original name, size) in a database table, as in Databases and GORM.

Go Upload handler with all three checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The traversal-looking name ../../notes.txt never reaches the file system, because the stored name is derived from the content hash. The second request exceeds the 64-byte body cap and is refused.

Downloads

To send a file Gin has c.File (inline, the browser may show it) and c.FileAttachment(path, "invoice.pdf") (forces a Save dialog). For generated data that never touches the disk, use c.DataFromReader:

Go
r.GET("/export.csv", func(c *gin.Context) {
	c.Header("Content-Disposition", `attachment; filename="users.csv"`)
	c.Data(http.StatusOK, "text/csv", csvBytes)
})

Authorize first: a download route needs the same checks as any API route, as covered in Authentication and Security.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which form attribute is required for a browser to upload a file?

    Without multipart/form-data the browser sends only the file name, not its bytes.
  2. 2. What does r.MaxMultipartMemory control in Gin?

    It is a memory threshold, not a limit. Enforce limits with http.MaxBytesReader and at the proxy.
  3. 3. Why should you not save a file under file.Filename?

    A malicious client can send names like ../../x or evil.php. Generate your own name.
  4. 4. Which function checks the real type of an uploaded file?

    DetectContentType sniffs the first 512 bytes. The declared extension and header can both be faked.

Summary

  • Uploads arrive as multipart/form-data; use c.FormFile for one file and c.MultipartForm for several.
  • Limit the body size with http.MaxBytesReader; MaxMultipartMemory is only a memory threshold.
  • Never trust the file name or declared type: sniff the content and store under a name you generate.
  • Send downloads with c.File, c.FileAttachment or c.Data, and authorize them.

Next: GORM: Setup and Models