简单记录一下自己在用gin上传图片接口

在官网上有相应的简单介绍
在这直接说
在请求方式上是POST,然后利用FormFile获取传值,

file,err := c.FormFile("file")
	if err != nil {
		errLog.Error(logrus.Fields{"err":err.Error(),"source":pkg.GetPath()},"controller - admin - upload")
		c.JSON(http.StatusOK,fmt.Sprintf("'%s' uploaded",file.Filename))
		return
	}

然后就是确定我们要将文件放在那个文件加下,这里是放在images文件夹下

filepath := path.Join("./"+config.BaseConf.Image.Dir,file.Filename)

限制上传文件类型

fileExt := strings.ToLower(path.Ext(file.Filename))
if fiileExt != ".png"{
c.JSON(http.StatusOK,gin.H{"uploading":"done","message":"上传图片不是png格式文件",}))
	return
}

然后就是保存图片

if err != nil {
		errLog.Error(logrus.Fields{"err":err.Error(),"source":pkg.GetPath()},"controller - admin - upload - SaveUploadedFile")
		c.JSON(http.StatusOK,err.Error())
		return
	}

最后返回,因为所需,所以返回的是url

c.JSON(http.StatusOK,gin.H{"uploading":"done","message":"success","url":"http://"+c.Request.Host+config.BaseConf.Image.Dir+file.Filename})

再返回url之前需要我们先将images文件夹变为静态文件夹可直接访问

r := gin.Default()
r.StaticFS("/images",http.Dir("./images"))

最后完整代码,由于我这里是自己练习前后端没有对上传文件做限制就不写了

package upload

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"go_service/config"
	errLog "go_service/log"
	"go_service/pkg"
	"net/http"
	"path"
)

//图片上传
func UploadImage(c *gin.Context)  {
	file,err := c.FormFile("file")
	if err != nil {
		errLog.Error(logrus.Fields{"err":err.Error(),"source":pkg.GetPath()},"controller - admin - upload")
		c.JSON(http.StatusOK,fmt.Sprintf("'%s' uploaded",file.Filename))
		return
	}

	filepath := path.Join("./"+config.BaseConf.Image.Dir,file.Filename)
	err = c.SaveUploadedFile(file,filepath)
	if err != nil {
		errLog.Error(logrus.Fields{"err":err.Error(),"source":pkg.GetPath()},"controller - admin - upload - SaveUploadedFile")
		c.JSON(http.StatusOK,err.Error())
		return
	}
	c.JSON(http.StatusOK,gin.H{"uploading":"done","message":"success","url":"http://"+c.Request.Host+config.BaseConf.Image.Dir+file.Filename})
}

文件和图片上传保存没啥区别

在内容中的log日志是自己利用logrus封装的日志:点击·
博主个人小博客:嘿嘿

 
·