导读 这篇文章主要为大家详细介绍了golang实现文件上传并转存数据库功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了golang实现文件上传并转存数据库的具体代码,供大家参考,具体内容如下

需求

上传图片,且可选择将图片保存到数据中。

一、流程图

二、步骤
1.上传文件接口

获取文件,并返回base64string流

代码如下(示例):

func setIconPost(c *gin.Context)  {
    //获取文件,icon实现对上传文件的访问,header是对上传文件信息的标记
    icon,header,err :=c.Request.FormFile("file")
    dangerous(err)
    defer icon.Close()
    //path.Ext是取后缀,Tolower小写
    ext := strings.ToLower(path.Ext(header.Filename))
    if header.Size>1024*1024*2{
        fmt.Println("文件过大")
    }
    buf := bytes.NewBuffer(nil)
    //读取icon的数据存入buf中
    if _,err := io.Copy(buf,icon);err != nil{
        return
    }
    //将base64返回前端
    renderData(c, gin.H{
        "base64":base64.StdEncoding.EncodeToString(buf.Bytes()),
        "icon-ext":ext,
    },nil)
}
2.存储数据

代码如下(示例):

func setEntPost(c *gin.Context)  {
    var f Identical
    bind(c,&f)
    models.EtpSave(f.Copyright,"copyright")
    models.EtpSave(f.Introduction,"introduction")
    models.EtpSave(f.Icon,"icon")
    models.EtpSave(f.Logo,"logo")
    models.EtpSave(f.Version,"version")
    models.EtpSave(f.Belong,"belong")
    renderMessage(c,nil)
}
3.存储的数据库操作
type Etp struct {
    Id    int         `json:"id"`
    Ckey  string     `json:"ckey"`
    Cval  string    `json:"cval"`
    Kind  int         `json:"kind"`
}
func EtpSave(cval, ckey string) error {
    var obj Etp
    //数据库是否存在
    has,err := DB["rdb"].Table("configs").Where("ckey=?",ckey).Get(&obj)
    if err != nil{
        return err
    }
    //不存在
    if !has {
        _, err = DB["rdb"].Table("configs").Where("ckey=?",ckey).Insert(Etp{
            Ckey: ckey,
            Cval: cval,
            Kind: 1,
        })
    }else{
        obj.Cval = cval
        DB["rdb"].Table("configs").Where("ckey=?",ckey).Cols("cval").Update(&obj)
    }
    return err
}
4.优化

若上传图片稍大,在转存MySQL时会报错。Data too long for column '......' at row 1

解决方法

将数据库字段格式设置为longtext

总结

本需求主要难点在于对于golang核心库方法的掌握,包括上传文件,[]bytes 和 string之间的转换。

整体框架:

一、接收文件/图片接口

二、修改/保存图片的接口

三、保存数据的方法

原文来自:https://www.jb51.net/article/256823.htm

本文地址:https://www.linuxprobe.com/golang-fale-linux.html编辑:倪家兴,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/