基于gin框架实现图片上传到七牛云并返回URL(接口的形式)

1.使用apifox模拟前端上传图片

基于gin框架实现图片上传到七牛云并返回URL(接口的形式)_第1张图片

2.参数校验(api层)

func UploadAvatarHandler(c *gin.Context) {
	file, fileHeader, _ := c.Request.FormFile("file")
	fileSize := fileHeader.Size
	resp ,err :=service.UserAvatarUpload(c.Request.Context(),file,fileSize,fileHeader.Filename)
	if err!=nil{
		log.LogrusObj.Infoln(err)
		response.FailWithMessage("上传头像时,出错了", c)
	}
	response.OkWithDetailed(resp,"上传头像成功",c)
}

3.逻辑处理(service层)

func UserAvatarUpload(c context.Context, file multipart.File, fileSize int64,name string) (resp interface{}, err error) {
	u, err := ctl.GetUserInfo(c)
	if err != nil {
		log.LogrusObj.Error(err)
		return nil, err
	}
	uId := u.Id
	userDao := mysql.NewUserDao(c)
	user, err := userDao.GetUserById(uId)
	if err != nil {
		log.LogrusObj.Error(err)
		return nil, err
	}
	//核心代码,上面的不用看
	var path string
	path, err = upload.UploadToQiNiu(file, fileSize,name)
	if err != nil {
		log.LogrusObj.Error(err)
		return nil, err
	}
	//下面的不用看,直接看4
	user.Avatar = path
	err = userDao.UpdateUserById(uId, user)
	if err != nil {
		log.LogrusObj.Error(err)
		return nil, err
	}
	return path, err
}

4.七牛云上传的相关代码

// UploadToQiNiu 封装上传图片到七牛云然后返回状态和图片的url,单张
func UploadToQiNiu(file multipart.File, fileSize int64, name string) (path string, err error) {
	qConfig := conf.Config.Oss
	var AccessKey = qConfig.AccessKeyId
	var SerectKey = qConfig.AccessKeySecret
	var Bucket = qConfig.BucketName
	var ImgUrl = qConfig.QiNiuServer //七牛云给你的域名
	putPlicy := storage.PutPolicy{
		Scope: Bucket,
	}
	mac := qbox.NewMac(AccessKey, SerectKey)
	upToken := putPlicy.UploadToken(mac)
	cfg := storage.Config{
		Zone:          &storage.ZoneHuanan,
		UseCdnDomains: false,
		UseHTTPS:      false,
	}
	putExtra := storage.PutExtra{}
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	uniqueFileName := generateUniqueFileName( name) //生成唯一名字,可用于一个文件重复上传
	err = formUploader.Put(context.Background(), &ret, upToken, uniqueFileName, file, fileSize, &putExtra)
	if err != nil {
		return "", err
	}
	url := ImgUrl + "/" + ret.Key
	return url, err
}
func generateUniqueFileName(originalName string) string {
	// 使用当前时间戳和原始文件名生成唯一文件名
	timestamp := time.Now().Unix()
	ext := filepath.Ext(originalName)
	nameWithoutExt := originalName[:len(originalName)-len(ext)]
	uniqueName := fmt.Sprintf("%s_%d%s", nameWithoutExt, timestamp, ext)
	return uniqueName
}

你可能感兴趣的:(gin,go)