如何通过 Postman 上传多个文件(RESOLVIDO)

d7v8vwbk  于 2022-11-29  发布在  Postman
关注(0)|答案(2)|浏览(355)

我正在用Go语言开发一个上传API。我可以通过postman一次上传一个文件,body〉〉form-data,但我不能上传超过1个文件,有解决方案吗?代码:

package main

import (
    "fmt"
    "mime/multipart"
    "net/http"
    "path/filepath"

    "github.com/gin-gonic/gin"
)

type BindFile struct {
    Name  string                `form:"name" binding:"required"`
    Email string                `form:"email" binding:"required"`
    File  *multipart.FileHeader `form:"file" binding:"required"`
}

func main() {
    router := gin.Default()

    router.POST("/upload", func(c *gin.Context) {
        var bindFile BindFile

        c.ShouldBind(&bindFile)
        file := bindFile.File
        dst := filepath.Base(file.Filename)
        c.SaveUploadedFile(file, dst)

        c.String(http.StatusOK, fmt.Sprintf("arquivo %s upado com sucesso", file.Filename))
    })
    router.Run(":8080")
}

我尝试在表单中放入一个文件数组-data:file[],但它不起作用

c90pui9n

c90pui9n1#

我设法解决它如下

package main

import (
    "net/http"
    "path/filepath"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    router.Static("/", ".public")
    router.POST("/", func(c *gin.Context) {

        form, _ := c.MultipartForm()

        files := form.File["files"]

        for _, file := range files {
            filename := filepath.Base(file.Filename)
            if err := c.SaveUploadedFile(file, filename); err != nil {
                c.String(http.StatusBadRequest, "erro ao carregar arquivo")
            }
        }
        c.String(http.StatusOK, "upload realizado, %d files ", len(files))
    })
    router.Run(":8080")
}

资料来源:
https://github.com/gin-gonic/examples/blob/master/upload-file/multiple/main.go

pbpqsu0x

pbpqsu0x2#

此代码片段似乎可以工作

package main

import (
    "github.com/gin-gonic/gin"
    "log"
    "mime/multipart"
)

type BindFile struct {
    Name  string                  `form:"name" binding:"required"`
    Email string                  `form:"email" binding:"required"`
    Files []*multipart.FileHeader `form:"file" binding:"required"`
}

func main() {
    router := gin.Default()

    router.POST("/upload", func(c *gin.Context) {
        var bindFile BindFile

        c.ShouldBind(&bindFile)
        for _, f := range bindFile.Files {
            log.Println(f.Filename)
        }
    })

    router.Run(":3000")
}

相关问题