1 package main 2 3 import ( 4 "fmt" 5 "net/http" 6 "path/filepath" 7 8 "github.com/gin-gonic/gin" 9 ) 10 11 func main() { 12 r := gin.Default() 13 // Set a lower memory limit for multipart forms, default is 32MB 14 r.MaxMultipartMemory = 8 << 20 // 8MB 15 r.Static("/", "./public") 16 r.POST("/upload", func(c *gin.Context) { 17 name := c.PostForm("name") 18 email := c.PostForm("email") 19 20 // Source 21 file, err := c.FormFile("file") 22 if err != nil { 23 c.String(http.StatusBadRequest, fmt.Sprintf("get form err: %s", err.Error())) 24 return 25 } 26 27 filename := filepath.Base(file.Filename) 28 if err := c.SaveUploadedFile(file, filename); err != nil { 29 c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error())) 30 return 31 } 32 c.String(http.StatusOK, 33 fmt.Sprintf("File %s uploaded successfully with fields name=%s and emails=%s.", file.Filename, name, email)) 34 }) 35 r.Run(":8080") 36 }
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>Single file upload</title> 6 </head> 7 <body> 8 <h1>Upload single file with fields</h1> 9 10 <form action="/upload" method="post" enctype="multipart/form-data"> 11 Name: <input type="text" name="name"><br> 12 Email: <input type="email" name="email"><br> 13 Files: <input type="file" name="file"<br><br> 14 <input type="submit" value="Submit"> 15 </form> 16 </body>
原文:https://www.cnblogs.com/chenguifeng/p/12203040.html