Skip to content

Gin File Upload: Form File vs Multipart

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about Gin File Upload: Form File vs Multipart. We cover key concepts, practical examples, and best practices.

File uploads in Gin -- Handle file uploads correctly using c.FormFile() with multipart/form-data form encoding.

The Problem

Gin's c.FormFile() requires Content-Type multipart/form-data. If the form uses application/x-www-form-urlencoded or is missing enctype, the file is not parsed.

Wrong

func uploadHandler(c *gin.Context) {
    file, err := c.FormFile("file")
    if err != nil {
        c.String(400, "no file")
        return
    }
    c.SaveUploadedFile(file, "./uploads/"+file.Filename)
}

Output:

$ curl -X POST http://localhost:8080/upload   -d "file=@photo.jpg"
// no file (missing -F flag)
func uploadHandler(c *gin.Context) {
    file, err := c.FormFile("file")
    if err != nil {
        c.String(400, err.Error())
        return
    }
    dst := filepath.Join("./uploads", file.Filename)
    if err := c.SaveUploadedFile(file, dst); err != nil {
        c.String(500, "upload failed")
        return
    }
    c.String(200, "Uploaded "+file.Filename)
}

Output:

$ curl -X POST http://localhost:8080/upload   -F "file=@photo.jpg"
Uploaded photo.jpg

Prevention

  • HTML forms need enctype="multipart/form-data"
  • Use curl -F "file=@path" not -d
  • Set MaxMultipartMemory on the engine for memory limits
  • Validate file type by checking content, not extension
  • Limit file size with http.MaxBytesReader()

Common Mistakes with gin file upload

  1. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
  2. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  3. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**How do I upload multiple files?**

Use c.MultipartForm() to get all files, then access File["field_name"].

How do I limit upload size?

Set r.MaxMultipartMemory = 8 << 20 (8MB).

Can I stream an upload?

Yes. Use c.Request.Body directly for streaming.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro