Read multipart-form data as []byte in GO

huangapple go评论88阅读模式
英文:

Read multipart-form data as []byte in GO

问题

我正在使用GIN作为GO框架,当我上传文件并直接将图像转换为字节以便将其存储在数据库表中的BLOB字段中时,遇到了一个问题。所以我的代码片段如下:

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

我尝试像这样将其存储在数据库中:

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

但是它返回了这种错误:

无法将file(类型为multipart.File)用作[]byte类型

英文:

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

答案1

得分: 33

*multipart.File 实现了 io.Reader 接口,因此你可以将其内容复制到 bytes.Buffer 中,方法如下:

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
}

// 然后将其添加到你的应用中
app.SetFile(buf.Bytes())
英文:

*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())

huangapple
  • 本文由 发表于 2017年3月13日 15:02:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/42758054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定