Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read multipart-form data as []byte in GO

I'm using GIN as GO framework, I'm having an issue when uploading file and directly convert image as byte so I can store it in my BLOB field inside db table, so I have my piece of code like this:

func (a *AppHandler) Upload(ctx *gin.Context) {

form := &struct {
    Name    string `form:"name" validate:"required"`
    Token   string `form:"token" validate:"required"`
    AppCode string `form:"app_code" validate:"required"`
}{}
ctx.Bind(form)
if validationErrors := a.ValidationService.ValidateForm(form); validationErrors != nil {
    httpValidationErrorResponse(ctx, validationErrors)
    return
}

file, header, err := ctx.Request.FormFile("file")

and I'm trying to store it in db like this

app.SetFile(file)
a.AppStore.Save(app)

and it returns this kind of error:

cannot use file (type multipart.File) as type []byte

like image 293
Aji Tirta Avatar asked Mar 13 '17 07:03

Aji Tirta


1 Answers

*multipart.File implements io.Reader interface so you could copy its content into a bytes.Buffer like this:

file, header, err := ctx.Request.FormFile("file")    
defer file.Close()
if err != nil {
    return nil, err
}

buf := bytes.NewBuffer(nil)
if _, err := io.Copy(buf, file); err != nil {
    return nil, err
}

and then add to your app

app.SetFile(buf.Bytes())
like image 76
Steve C Avatar answered Nov 11 '22 02:11

Steve C