Aji*_*rta 3 blob file-upload go go-gorm
我使用GIN作为GO框架,在上传文件并将图像直接转换为字节时出现即时通讯问题,因此我可以将其存储在db表中的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")
Run Code Online (Sandbox Code Playgroud)
我试图像这样将其存储在数据库中
app.SetFile(file)
a.AppStore.Save(app)
Run Code Online (Sandbox Code Playgroud)
它返回这种错误:
cannot use file (type multipart.File) as type []byte
Run Code Online (Sandbox Code Playgroud)
那么如何解决呢?我使用Go语言非常新
注意:我的数据库ORM也使用了GORM
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
}
Run Code Online (Sandbox Code Playgroud)
然后添加到您的应用中
app.SetFile(buf.Bytes())
Run Code Online (Sandbox Code Playgroud)