Gin File Upload: Single and Multi-File Handling with Security Checks
Gin Uploading Files
Uploads use multipart/form-data: the browser splits the file into chunks and puts them in the request body; the server pulls the files out by form field name and writes them to disk.
Follow along in order:
- Single file upload
- Validating size and extension
- Multiple file upload
The DefaultPostForm from the previous chapter only reads regular form fields, not files. For files, use FormFile or MultipartForm.
1. Single file upload
The server reads files by the same field name used by the frontend. Here, the field is file:
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">Upload</button>
</form>
enctype="multipart/form-data" is required, otherwise the body won't contain the file.
router.POST("/upload", func(ctx *gin.Context) {
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// etc/static/1.png → 1.png, keep only the filename
dst := filepath.Join("./files/", filepath.Base(file.Filename))
if err := ctx.SaveUploadedFile(file, dst); err != nil {
ctx.String(http.StatusInternalServerError, "Save failed")
return
}
ctx.String(http.StatusOK, "Upload succeeded")
})
| API | Function |
|---|---|
ctx.FormFile("file") |
Gets one file by field name. Returns a *multipart.FileHeader containing the original filename and size |
file.Filename |
The filename provided by the client, which may include a directory, e.g., etc/static/1.png |
filepath.Base(file.Filename) |
Keeps only the last segment: etc/static/1.png → 1.png |
filepath.Join("./files/", filename) |
Builds the destination path files/1.png. The separator follows the current OS |
ctx.SaveUploadedFile(file, dst) |
Writes the file to dst. If the parent directory doesn't exist, it creates it |
Base is important. A client can send ../ or an entire path; if you join file.Filename directly, the file lands outside ./files/. Base strips the directory and keeps only a name like 1.png, which is then joined with ./files/.
Check the error from SaveUploadedFile. If saving fails and you continue to respond with "Upload succeeded", the client sees a wrong result.
Test with curl (-F automatically adds multipart/form-data):
curl -F "[email protected]" http://localhost:8080/upload
file= maps to FormFile("file"), and @1.png tells curl to upload the local file 1.png. After success, files/1.png appears in the project.
2. Validating size and extension
After the file is retrieved, before writing to disk, two checks run: sizes too large are discarded, and extensions not in the whitelist are rejected.
Size: 5 << 20 is 5MB
<< is left shift. Moving bits left by n places multiplies the value by 2 to the power of n. Since file sizes in memory are in bytes, shifts express KB, MB, and GB:
| Notation | Equals | Meaning |
|---|---|---|
1 << 10 |
1024 bytes | 1KB |
1 << 20 |
1024 × 1024 bytes | 1MB |
1 << 30 |
1024 × 1024 × 1024 bytes | 1GB |
5 << 20 |
5 × 1MB | 5MB |
The shift count determines the unit: 10 for KB, 20 for MB, 30 for GB. The number before the shift is the count in that unit. 5 << 20 is 5MB.
const MaxSize = 5 << 20 // 5MB
if file.Size > MaxSize {
ctx.String(http.StatusRequestEntityTooLarge, "File too large")
return
}
file.Size is in bytes. If it exceeds 5MB, return 413 (StatusRequestEntityTooLarge), then return stops the save.
Extension: only png and jpg allowed
Use a map as a whitelist; lookups are O(1), and absent keys read as false:
var allowExt = map[string]bool{
".png": true,
".jpg": true,
}
ext := strings.ToLower(filepath.Ext(file.Filename))
if !allowExt[ext] {
ctx.String(http.StatusBadRequest, "This extension is not supported yet")
return
}
filepath.Ext includes the dot; "1.png" gives ".png", so the whitelist keys are written as ".png", not "png".
Extension case varies; Windows often sends .PNG, .JPG. Ext does not lowercase for you, so use strings.ToLower before comparing, otherwise valid images get rejected.
Both checks run before SaveUploadedFile:
router.POST("/upload", func(ctx *gin.Context) {
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if file.Size > MaxSize {
ctx.String(http.StatusRequestEntityTooLarge, "File too large")
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
if !allowExt[ext] {
ctx.String(http.StatusBadRequest, "This extension is not supported yet")
return
}
dst := filepath.Join("./files/", filepath.Base(file.Filename))
if err := ctx.SaveUploadedFile(file, dst); err != nil {
ctx.String(http.StatusInternalServerError, "Save failed")
return
}
ctx.String(http.StatusOK, "Upload succeeded")
})
| Request | Result |
|---|---|
1.png, under 5MB |
files/1.png, response "Upload succeeded" |
| 6MB png | 413, "File too large", no file on disk |
1.gif |
400, "This extension is not supported yet" |
photo.JPG |
Lowercased to .jpg, allowed and saved |
3. Multiple file upload
When multiple files are selected at once, FormFile only grabs the first one for that field. Use MultipartForm to parse the whole package, then fetch the file slice by field name.
Change the frontend field to files and add multiple:
<input type="file" name="files" multiple>
form, err := ctx.MultipartForm()
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
files := form.File["files"]
form.File is of type map[string][]*multipart.FileHeader. The key is the field name "files", and the value is all files under that field. If the field name doesn't match the frontend name, the value is nil, and the loop never runs.
Size and extension checks are the same as for a single file, placed inside the loop so each file is checked individually. If one fails, return immediately, skipping the rest:
router.POST("/upload", func(ctx *gin.Context) {
form, err := ctx.MultipartForm()
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
files := form.File["files"]
if len(files) == 0 {
ctx.String(http.StatusBadRequest, "No file")
return
}
for _, file := range files {
if file.Size > MaxSize {
ctx.String(http.StatusRequestEntityTooLarge, "File too large")
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
if !allowExt[ext] {
ctx.String(http.StatusBadRequest, "This extension is not supported yet")
return
}
dst := filepath.Join("./files/", filepath.Base(file.Filename))
if err := ctx.SaveUploadedFile(file, dst); err != nil {
ctx.String(http.StatusInternalServerError, "Save failed")
return
}
}
ctx.String(http.StatusOK, "Upload succeeded")
})
Send the success response only after the loop ends. If it were inside the loop, the response would finish after the first file was saved.
Upload two files together:
curl -F "[email protected]" -F "[email protected]" http://localhost:8080/upload
Both -F flags use the same field name files, matching form.File["files"].
All together
package main
import (
"net/http"
"path/filepath"
"strings"
"github.com/gin-gonic/gin"
)
// 1 << 10 is 1KB, 1 << 20 is 1MB, 1 << 30 is 1GB
const MaxSize = 5 << 20 // 5MB
var allowExt = map[string]bool{
".png": true,
".jpg": true,
}
func main() {
router := gin.Default()
router.POST("/upload", func(ctx *gin.Context) {
form, err := ctx.MultipartForm()
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
files := form.File["files"]
if len(files) == 0 {
ctx.String(http.StatusBadRequest, "No file")
return
}
for _, file := range files {
if file.Size > MaxSize {
ctx.String(http.StatusRequestEntityTooLarge, "File too large")
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
if !allowExt[ext] {
ctx.String(http.StatusBadRequest, "This extension is not supported yet")
return
}
dst := filepath.Join("./files/", filepath.Base(file.Filename))
if err := ctx.SaveUploadedFile(file, dst); err != nil {
ctx.String(http.StatusInternalServerError, "Save failed")
return
}
}
ctx.String(http.StatusOK, "Upload succeeded")
})
if err := router.Run(); err != nil {
panic(err)
}
}
For a single file, the same endpoint works; the field name is still files:
curl -F "[email protected]" http://localhost:8080/upload
The single-file FormFile("file") from the earlier section fits an endpoint that expects exactly one file; use MultipartForm for multiple files.
Summary
| Topic | Remember |
|---|---|
| Single file | ctx.FormFile("file"), field name matches the frontend name |
| Saving | filepath.Join("./files/", filepath.Base(file.Filename)), Base strips client-supplied directories |
| Save error | ctx.SaveUploadedFile(file, dst), return on error |
| Size | 5 << 20 is 5MB. 10 / 20 / 30 correspond to KB / MB / GB. Return 413 when over limit |
| Extension | filepath.Ext includes the dot, whitelist keys like ".png". Use strings.ToLower before comparing |
| Multiple files | ctx.MultipartForm(), get the slice with form.File["files"], run the same validation in the loop then save |
Top 1 from juejin.cn, machine-translated. The original thread is authoritative.
For files with the same name, it is recommended to generate a unique storage name.