doujuxin7392 2017-03-13 07:02
浏览 269
已采纳

在GO中以[] byte读取多部分形式的数据

I'm using GIN as GO framework, im 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 im 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 

so how to fix this? im pretty new with Go language
NOTE: i'm using GORM as well for my db ORM

  • 写回答

1条回答 默认 最新

  • duanhuhong5255 2017-03-13 07:19
    关注

    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())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看