介绍
本节列出了上传文件的 api 用法,具体包括同时上传单个文件和同时上传多个文件,并将文件保存到项目当前目录。
案例
源码:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"log"
)
func main() {
r := gin.Default()
// 为 multipart forms 设置较低的内存限制 (默认是 32 MiB)
r.MaxMultipartMemory = 8 << 20
r.POST("/upload/single", func(c *gin.Context) {
file, _ := c.FormFile("file")
log.Println(file.Filename)
dst := "./" + file.Filename
c.SaveUploadedFile(file, dst)
c.String(200, fmt.Sprintf("'%s' uploaded", file.Filename))
})
r.POST("/upload/multi", func(c *gin.Context) {
form, _ := c.MultipartForm()
files := form.File["upload[]"]
for _, file := range files {
log.Println(file.Filename)
dst := "./" + file.Filename
c.SaveUploadedFile(file, dst)
}
c.String(200, fmt.Sprintf("'%d' files uploaded!", len(files)))
})
r.Run(":8080")
}
测试:
单个文件:
$ curl -X POST http://localhost:8080/upload/single \
-F "file=@/home/xg/test1.txt" \
-H "Content-Type: multipart/form-data"
输出:
'test1.txt' uploaded
多个文件:
$ curl -X POST http://localhost:8080/upload/multi \
-F "upload[]=@/home/xg/test2.txt" \
-F "upload[]=@/home/xg/test3.txt" \
-H "Content-Type: multipart/form-data"
输出:
'2' files uploaded!
下载到当前目录:
$ ls
go.mod go.sum main.go test1.txt test2.txt test3.txt