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")
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM