Gin File Upload: Single and Multi-File Handling with Security Checks
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.
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.
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.
For files with the same name, it is recommended to generate a unique storage name.