How do I handle file uploads with Gin in Go?

Handling file uploads in Go using the Gin framework is straightforward. Gin provides a way to handle multipart forms, which can include file uploads. Below is a simple example of how to set up a file upload feature in a Gin web application.

package main import ( "github.com/gin-gonic/gin" "net/http" "os" ) func main() { r := gin.Default() r.POST("/upload", func(c *gin.Context) { // Get the file from the request file, err := c.FormFile("file") if err != nil { c.String(http.StatusBadRequest, "Bad request: %s", err.Error()) return } // Save the file to a specific location if err := c.SaveUploadedFile(file, "./uploads/"+file.Filename); err != nil { c.String(http.StatusInternalServerError, "Could not save file: %s", err.Error()) return } c.String(http.StatusOK, "File uploaded successfully: %s", file.Filename) }) // Start the server r.Run(":8080") // listen and serve on :8080 }

file upload Gin Go language multipart form web application