2019-03-21 Gin框架入门02

1.curl模拟常见的场景


  • 1.application/json (request中发送json数据用post方式发送Content-type用application/json)
  • 2.application/x-www-form-urlencoded(常见的表达提交,把query string的内容 放到的body体内,同样需要urlencoded)
  • 3.application/xml (http作为传输协议,xml作为编码方式远程调用规范)
  • 4.multipart/form-data(图片上传)

2. 单文件上传

示例

package main

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

func main() {
    router := gin.Default()
    // 给表单限制上传大小 (默认 32 MiB)
    router.MaxMultipartMemory =8M << 20 M // 8 MiB

    router.POST("/upload", func(c *gin.Context) {
        //name := c.PostForm("name")
        //fmt.Println(name)

        file, err := c.FormFile("file")    //file, err := c.FormFile("file")获取文件
        log.Println(file.Filename)

        //单文件上传
        if err != nil {
            c.String(http.StatusBadRequest, "a bad request")
            return
        }

        if err := c.SaveUploadedFile(file, file.Filename); err != nil{
            c.String(http.StatusBadRequest, "upload file err:%s", err.Error())
            return
        }

        filename := file.Filename      //filename := file.Filename获取文件名
        c.String(http.StatusCreated, "%s upload successful", filename)

    })
    router.Run(":8081")
}

3. 多文件上传

示例

package  main

import (
    "github.com/gin-gonic/gin"
    "io"
    "log"
    "net/http"
    "os"
)

func main() {

    router := gin.Default()

    // 给表单限制上传大小 (默认 32 MiB)
    // router.MaxMultipartMemory = 8 << 20  // 8 MiB

    router.POST("/upload", func(c *gin.Context) {
        err := c.Request.ParseMultipartForm(200000)
        if err != nil {
            log.Fatal(err)
        }

        formdata := c.Request.MultipartForm
        files := formdata.File["upload"]

        for i, _ :=range files {
            file, err := files[i].Open()
            defer  file.Close()
            if err != nil {
                log.Fatal(err)
            }

            out, err := os.Create(files[i].Filename)

            defer out.Close()

            if err != nil {
                log.Fatal(err)
            }

            _, err = io.Copy(out, file)

            if err != nil {
                log.Fatal(err)
            }

            c.String(http.StatusCreated, "upload successful")

        }

    })

    router.Run(":8082")
}

你可能感兴趣的:(2019-03-21 Gin框架入门02)