- multipart/form-data格式用于文件上传
- gin文件上传与原生的net/http方法类似,不同在于gin把原生的request封装到c.Request中
```go package main<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
上传文件:<input type="file" name="file" >
<input type="submit" value="提交">
</form>
</body>
</html>
import ( “github.com/gin-gonic/gin” )
func main() { r := gin.Default() //限制上传最大尺寸 r.MaxMultipartMemory = 8 << 20 r.POST(“/upload”, func(c *gin.Context) { file, err := c.FormFile(“file”) if err != nil { c.String(500, “上传图片出错”) } // c.JSON(200, gin.H{“message”: file.Header.Context}) c.SaveUploadedFile(file, file.Filename) c.String(http.StatusOK, file.Filename) }) r.Run() }
效果演示:<br />![](https://cdn.nlark.com/yuque/0/2021/png/12774153/1623514827787-2021efbc-a26d-41cd-984c-4fd94266e634.png#clientId=u22975bc8-803c-4&from=paste&id=uf8c9773b&margin=%5Bobject%20Object%5D&originHeight=182&originWidth=648&originalType=url&ratio=2&status=done&style=none&taskId=ued113d2e-0c26-420d-96d1-dd70bbec67e)<br />![](https://cdn.nlark.com/yuque/0/2021/png/12774153/1623514827774-f905e83a-4d41-4f3a-86ca-23fda5ed9eb1.png#clientId=u22975bc8-803c-4&from=paste&id=u2f2c16b2&margin=%5Bobject%20Object%5D&originHeight=242&originWidth=485&originalType=url&ratio=2&status=done&style=none&taskId=uba7b1538-6268-4253-8f88-e643aec119c)
<a name="LIE7t"></a>
### 上传特定文件
有的用户上传文件需要限制上传文件的类型以及上传文件的大小,但是gin框架暂时没有这些函数(也有可能是我没找到),因此基于原生的函数写法自己写了一个可以限制大小以及文件类型的上传函数
```go
package main
import (
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.POST("/upload", func(c *gin.Context) {
_, headers, err := c.Request.FormFile("file")
if err != nil {
log.Printf("Error when try to get file: %v", err)
}
//headers.Size 获取文件大小
if headers.Size > 1024*1024*2 {
fmt.Println("文件太大了")
return
}
//headers.Header.Get("Content-Type")获取上传文件的类型
if headers.Header.Get("Content-Type") != "image/png" {
fmt.Println("只允许上传png图片")
return
}
c.SaveUploadedFile(headers, "./video/"+headers.Filename)
c.String(http.StatusOK, headers.Filename)
})
r.Run()
}