mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-21 16:58:08 +08:00
update readme: add multipart file binding
This commit is contained in:
parent
e8a1e2fc23
commit
1463acc1b1
38
README.md
38
README.md
@ -959,32 +959,36 @@ result:
|
|||||||
### Multipart/Urlencoded binding
|
### Multipart/Urlencoded binding
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
type ProfileForm struct {
|
||||||
|
Name string `form:"name" binding:"required"`
|
||||||
|
Avatar *multipart.FileHeader `form:"avatar" binding:"required"`
|
||||||
|
|
||||||
import (
|
// or for multiple files
|
||||||
"github.com/gin-gonic/gin"
|
// Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`
|
||||||
)
|
|
||||||
|
|
||||||
type LoginForm struct {
|
|
||||||
User string `form:"user" binding:"required"`
|
|
||||||
Password string `form:"password" binding:"required"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
router := gin.Default()
|
router := gin.Default()
|
||||||
router.POST("/login", func(c *gin.Context) {
|
router.POST("/profile", func(c *gin.Context) {
|
||||||
// you can bind multipart form with explicit binding declaration:
|
// you can bind multipart form with explicit binding declaration:
|
||||||
// c.ShouldBindWith(&form, binding.Form)
|
// c.ShouldBindWith(&form, binding.Form)
|
||||||
// or you can simply use autobinding with ShouldBind method:
|
// or you can simply use autobinding with ShouldBind method:
|
||||||
var form LoginForm
|
var form ProfileForm
|
||||||
// in this case proper binding will be automatically selected
|
// in this case proper binding will be automatically selected
|
||||||
if c.ShouldBind(&form) == nil {
|
if err := c.ShouldBind(&form); err != nil {
|
||||||
if form.User == "user" && form.Password == "password" {
|
c.String(http.StatusBadRequest, "bad request")
|
||||||
c.JSON(200, gin.H{"status": "you are logged in"})
|
return
|
||||||
} else {
|
|
||||||
c.JSON(401, gin.H{"status": "unauthorized"})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)
|
||||||
|
if err != nil {
|
||||||
|
c.String(http.StatusInternalServerError, "unknown error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// db.Save(&form)
|
||||||
|
|
||||||
|
c.String(http.StatusOK, "ok")
|
||||||
})
|
})
|
||||||
router.Run(":8080")
|
router.Run(":8080")
|
||||||
}
|
}
|
||||||
@ -992,7 +996,7 @@ func main() {
|
|||||||
|
|
||||||
Test it with:
|
Test it with:
|
||||||
```sh
|
```sh
|
||||||
$ curl -v --form user=user --form password=password http://localhost:8080/login
|
$ curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile
|
||||||
```
|
```
|
||||||
|
|
||||||
### XML, JSON, YAML and ProtoBuf rendering
|
### XML, JSON, YAML and ProtoBuf rendering
|
||||||
|
Loading…
x
Reference in New Issue
Block a user