I tried to binding multipart.FileHeader to struct but not working, help plz!! I send request used Postman:

post_information_1 post_information_2

  • Go Version: go 1.12 linux/amd64
  • Operating System: Ubuntu 16.04

This is code:

Struct:

ExtractAttributeRequest struct {
        Image       *multipart.FileHeader `form:"image" binding:"required"`
        ImageBase64 string                `form:"image_base64"`
}

Binding part:

var req ExtractAttributeRequest
err := c.MustBindWith(&req, binding.FormMultipart)

And i got this error message: Key: 'ExtractAttributeRequest.Image' Error:Field validation for 'Image' failed on the 'required' tag

Comment From: vkd

I cannot reproduce this error.

gin branch: master

func main() {
    r := gin.New()
    r.POST("/", func(c *gin.Context) {
        var req struct {
            Image       *multipart.FileHeader `form:"image" binding:"required"`
            ImageBase64 string                `form:"image_base64"`
        }
        err := c.MustBindWith(&req, binding.FormMultipart)
        if err != nil {
            c.String(500, "error: %v\n", err)
            return
        }
        c.String(200, "ok\n")
    })
    r.Run(":8000")
}
$ curl localhost:8000 -X POST -H "Content-Type:multipart/form-data" -F "image=@/home/user/image.jpg"
ok

Can you give more examples? What version of gin are you using?

Comment From: yai-dev

I cannot reproduce this error.

gin branch: master

func main() { r := gin.New() r.POST("/", func(c *gin.Context) { var req struct { Image *multipart.FileHeader `form:"image" binding:"required"` ImageBase64 string `form:"image_base64"` } err := c.MustBindWith(&req, binding.FormMultipart) if err != nil { c.String(500, "error: %v\n", err) return } c.String(200, "ok\n") }) r.Run(":8000") } $ curl localhost:8000 -X POST -H "Content-Type:multipart/form-data" -F "image=@/home/user/image.jpg" ok Can you give more examples? What version of gin are you using?

Thank you for your reply, my gin version is v1.3.0, I will try to use master branch.

Comment From: uneight

@thinkerou Can i use shouldbind for not require file filed? If i use omitempty and not present the file field, i get message "http: no such file"

Comment From: thinkerou

@uneight please see the example https://github.com/gin-gonic/examples/tree/master/file-binding thanks!

Comment From: jimmy-insignia

@uneight @thinkerou I also have this problem and already see the example and still get an error. if I want to make file Optional, I still get error "http: no such file". how can I bind optional file to struct?

My code:

// UpdateUserRequest UpdateUserRequest
type UpdateUserRequest struct {
    CV              *multipart.FileHeader `form:"cv" binding:"omitempty"`
}

var params datatransfers.UpdateUserRequest
if err := c.ShouldBind(&params); err != nil {
    c.Error(err)
    return
}

If I don't put cv in request, it returned "http: no such file", but it's working just fine if I put cv in request