golangWEB框架gin学习之获取post参数

原文地址:http://www.niu12.com/article/41

package main

import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)

func postParams(c *gin.Context) {
// 表单发送 name=card, job=phper
name := c.PostForm("name")
job := c.PostForm("job")
c.JSON(http.StatusOK, gin.H{
"method": c.Request.Method,
"name": name,
"job": job,
})
// c.PostFormArray()、c.PostFormMap()、c.DefaultPostForm()的用法作用同GET相同
}

// 单文件上传
func postFile(c *gin.Context) {
file,err := c.FormFile("picture")
if err != nil {
panic(err)
}
// map[
// Content-Disposition:
// [form-data; name="picture"; filename="20170713121902724.gif"]
// Content-Type:[image/gif]
// ]
fmt.Println(file.Header)
// 298866
fmt.Println(file.Size)
// name:20170713121902724.gif
c.String(http.StatusOK, "name:" + file.Filename)
}

func postMultipleFile(c *gin.Context) {
form, err := c.MultipartForm()
if err != nil {
panic(err)
}
files := form.File["picture[]"]
// [0xc0421a80a0 0xc0421a80f0]
fmt.Println(files)
// 20170713121902724.gif
// 1_1536740500_x0IW0YfFJG.jpg
for _, file := range files{
fmt.Println(file.Filename)
}
}

func main() {
router := gin.Default()
router.POST("/post", postParams)

//获取文件
// 默认限制大小为32M
// 通过router.MaxMultipartMemory = 8 << 20 8M设置

// 单文件上传
router.POST("/upload", postFile)

// 多文件上传
router.POST("/uploadMultiple", postMultipleFile)
router.Run(":8888")
}
原文地址:https://www.cnblogs.com/zhouqi666/p/9808604.html