Gin File Upload: Form File vs Multipart
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)
Right
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
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - 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
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