Gin 表单与文件上传
表单参数
表单传输为 POST 请求,http 常见的传输格式为四种:
- application/json
- application/x-www-form-urlencoded
- application/xml
- multipart/form-data
表单参数可以通过 PostForm() 方法获取,该方法默认解析的是 x-www-form-urlencoded 或 form-data 格式的参数。
简单的表单示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo1</title>
</head>
<body>
<form action="http://localhost:8080/form" method="post" enctype="application/x-www-form-urlencoded">
用户名:<inpurt type="text" name="username" placeholder="请输入你的用户名"> <br>
密 码:<input type="password" name="password" placeholder="请输入你的密码"> <br>
<input type="submit" value="提交">
</form>
</body>
</html>
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
//表单参数
func main(){
r:=gin.Default()
r.POST("/form", func(c *gin.Context) {
types:=c.DefaultPostForm("type","post")
// 键名和html页面属性名对应
username:=c.PostForm("username")
password:=c.PostForm("userpassword")
c.String(http.StatusOK,fmt.Sprintf("username:%s,password:%s,types:%s",username,password,types))
})
r.Run()
}