Home > Enterprise >  How to upload many files via postman (RESOLVIDO)
How to upload many files via postman (RESOLVIDO)

Time:11-24

I am developing an upload api using Go. I can upload one file at a time via postman with body >> form-data but I can't upload more than 1 file, any solution? code:

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

I tried to put a file array in my form-data: file[] but it didn't work

CodePudding user response:

This snippet seems to work

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

enter image description here

CodePudding user response:

I managed to solve it as follows

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

source:

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

  • Related