跪拜 Guibai
← All articles
Backend · Go

Gin File Upload: Single and Multi-File Handling with Security Checks

By 小满zs ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Path traversal remains a common vulnerability in upload endpoints; stripping client-provided directory components with filepath.Base is the minimal guard that prevents files from landing outside the upload directory. The same pattern applies to any Go backend accepting user files, not just Gin.

Summary

Gin's upload flow starts with ctx.FormFile for a single file or ctx.MultipartForm for batches, then saves through SaveUploadedFile. Before anything touches disk, a 5MB limit written as 5 << 20 and an extension whitelist keyed on lowercase ".png" and ".jpg" are enforced.

Client filenames can carry directory components or ../ sequences, and joining those directly writes outside the intended folder, so filepath.Base must strip the path. Each validation failure bails early with its own status code: 413 for oversized files, 400 for unsupported extensions, 500 if saving fails. The multi-file loop applies the same per-file checks and only sends a success response after the entire loop finishes.

Curl commands demonstrate both single and batch uploads, with the field name deciding whether FormFile or MultipartForm handles the request.

Takeaways
— Use ctx.FormFile for a single file, keyed by the form field name.
— For multiple files, call ctx.MultipartForm and read form.File["files"] as a slice of *multipart.FileHeader.
— Sanitize the client-supplied filename with filepath.Base before joining it to the target directory.
— Set a size limit like 5 << 20 bytes (5MB) and return 413 when exceeded.
— Whitelist extensions using a map keyed by strings like ".png" and normalize case with strings.ToLower.
— Check SaveUploadedFile's error; a failed save should return 500, not a success message.
— In batch uploads, reject the entire request on the first failing file, and send the success response only after the loop completes.
Conclusions

Path traversal is treated as a default risk in upload endpoints, a sensible stance that many examples skip, leaving a write-anywhere hole.

Returning early on any invalid file in a batch keeps partial uploads from silently reporting success, which is exactly the behavior a client expects from a single API call.

Concepts & terms
multipart/form-data
A media type used for HTTP forms that can carry binary file data, splitting the body into parts each with its own name.
FileHeader
A Go struct holding metadata for an uploaded file, including the original filename and size, returned by Gin's FormFile and MultipartForm.
filepath.Base
A Go function returning the last element of a file path, stripping directory components; used here to discard any directory prefixes or traversal sequences a client might supply.
From the discussion
Featured comments
卷土的土

For files with the same name, it is recommended to generate a unique storage name.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗