1. 上传单文件

// FormFile returns the first file for the provided form key.
func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {
if c.Request.MultipartForm == nil {
if err := c.Request.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil {
return nil, err
}
}
f, fh, err := c.Request.FormFile(name)
if err != nil {
return nil, err
}
f.Close()
return fh, err
}
// SaveUploadedFile uploads the form file to specific dst.
func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error {
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()


out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()


_, err = io.Copy(out, src)
return err
}
package main


import (
"fmt"
"log"
"net/http"


"github.com/gin-gonic/gin"
)


func main() {
r := gin.Default()
// 设置文件上传大小限制,默认是32m
r.MaxMultipartMemory = 64 << 20 // 64MiB


  r.POST("/upload", func(c *gin.Context) {
file, _ := c.FormFile("file")

// 打印上传的文件名
log.Println(file.Filename)
// 将上传的文件,保存到./upload/1111.jpg 文件中
path := "./upload/" + file.Filename
c.SaveUploadedFile(file, path)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!!!", file.Filename))
})


r.Run()
}

现在,让我们使用postman模拟上传一个文件:

 


 

可以看到成功上传了:

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.


[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] POST   /upload                   --> main.main.func1 (3 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
2021/10/13 18:36:31 80b3d377da26e626.jpg
[GIN] 2021/10/13 - 18:36:31 | 200 | 33.8653ms | 127.0.0.1 | POST "/upload"