gin上传文件


 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>

上传多文件

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "log"
 6     "net/http"
 7     "path/filepath"
 8 
 9     "github.com/gin-gonic/gin"
10 )
11 
12 func main() {
13     router := gin.Default()
14     // 为 multipart forms 设置较低的内存限制 (默认是 32 MiB)
15     // router.MaxMultipartMemory = 8 << 20  // 8 MiB
16     router.POST("/upload", func(c *gin.Context) {
17         // Multipart form
18         form, _ := c.MultipartForm()
19         files := form.File["upload[]"]
20 
21         for _, file := range files {
22             log.Println(file.Filename)
23             filename := filepath.Base(file.Filename)
24             // 上传文件至指定目录
25             if err := c.SaveUploadedFile(file, filename); err != nil {
26                 c.String(http.StatusBadRequest, fmt.Sprintf("upload file err: %s", err.Error()))
27                 return
28             }
29         }
30         c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
31     })
32     router.Run(":8080")
33 }

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM