一、腾讯云对象存储COS
1. 创建储存桶
然后直接下一步-创建即可。
2. API密钥创建
3. 查看代码中需要的东西
- 储存桶名称Bucket、所属地域Region
- 密钥
APPID
、SecretId
、SecretKey
二、代码
1. 配置文件conf.toml
这里读取配置文件的第三方库是Viper,学习可以查看:viper库快速使用
将上面查看的几个值写入配置文件对应位置即可
[tencentCOS] # TencentCloud 腾讯云 # 储存桶名称 COS_BUCKET_NAME = "" # 所属地域 COS_REGION = "" # 密钥:APPID COS_APP_ID = "" # 密钥:SecretId COS_SECRET_ID = "" # 密钥:SecretKey COS_SECRET_KEY = "" # 此项固定 COS_URL_FORMAT = "http://%s-%s.cos.%s.myqcloud.com"
2. utils/tencent_cloud_cos.go
package util import ( "context" "fmt" "io" "log" "net/http" "net/url" "github.com/spf13/viper" "github.com/tencentyun/cos-go-sdk-v5" "github.com/tencentyun/cos-go-sdk-v5/debug" ) // getCos // @Title getCos // @Description 获取腾讯云Cos // @Author hyy 2022-03-04 18:39:29 // @Return *cos.Client func getCos() *cos.Client { u, _ := url.Parse(fmt.Sprintf( viper.GetString("tencentCOS.COS_URL_FORMAT"), viper.Get("tencentCOS.COS_BUCKET_NAME"), viper.Get("tencentCOS.COS_APP_ID"), viper.Get("tencentCOS.COS_REGION"), )) b := &cos.BaseURL{BucketURL: u} c := cos.NewClient(b, &http.Client{ Transport: &cos.AuthorizationTransport{ SecretID: viper.GetString("tencentCOS.COS_SECRET_ID"), SecretKey: viper.GetString("tencentCOS.COS_SECRET_KEY"), Transport: &debug.DebugRequestTransport{ RequestHeader: true, RequestBody: false, ResponseHeader: true, ResponseBody: true, Writer: nil, }, }, }) return c } // CheckErr // @Title CheckErr // @Description 检查错误 // @Author hyy 2022-03-04 18:39:49 // @Param err type description // @Return bool func CheckErr(err error) bool { if err == nil { return true } if cos.IsNotFoundError(err) { // WARN log.Println("WARN: Resource is not existed") return false } else if e, ok := cos.IsCOSError(err); ok { log.Println(fmt.Sprintf("ERROR: Code: %v\n", e.Code)) log.Println(fmt.Sprintf("ERROR: Message: %v\n", e.Message)) log.Println(fmt.Sprintf("ERROR: Resource: %v\n", e.Resource)) log.Println(fmt.Sprintf("ERROR: RequestID: %v\n", e.RequestID)) return false // ERROR } else { log.Println(fmt.Sprintf("ERROR: %v\n", err)) return false // ERROR } } // Upload // @Title Upload // @Description "上传文件" // @Param fileName 文件名 // @return bool "上传是否成功" func Upload(fileName string, file io.Reader) string { c := getCos() _, err := c.Object.Put(context.Background(), fileName, file, nil) if CheckErr(err) { return fmt.Sprintf( viper.GetString("tencentCOS.COS_URL_FORMAT")+"/%v", viper.GetString("tencentCOS.COS_BUCKET_NAME"), viper.GetString("tencentCOS.COS_APP_ID"), viper.GetString("tencentCOS.COS_REGION"), fileName, ) } return "" } // Delete // @Title Delete // @Description "删除文件" // @Param fileName string "想要删除的文件名 如:xx.png" // @return bool "删除是否成功" func Delete(fileName string) bool { c := getCos() _, err := c.Object.Delete(context.Background(), fileName, nil) return CheckErr(err) }
3.controller/tencent_cloud_cos_controller.go
package controller import ( "ginstudy02/util" "github.com/gin-gonic/gin" "log" "net/http" ) // Upload // @Summary Upload // @Description 腾讯云上传图片 // @Accept json // @Produce json // @Author hyy 2022-03-03 19:30:37 // @Param file body interface{} true "想要上传的文件" // @Router /v1/tencentCos [post] func Upload(c *gin.Context) { file, err := c.FormFile("file") if err != nil { log.Println(err) c.JSON(http.StatusBadRequest, gin.H{ "msg": "上传失败", "ERROR-CONTROLLER": err, }) return } fileType := file.Header["Content-Type"][0] if fileType != "image/png" && fileType != "image/jpg" && fileType != "image/jpeg" && fileType != "image/gif" { log.Println("上传图片非jpg,png,jpeg,gif,请重新上传!") c.JSON(http.StatusBadRequest, gin.H{ "msg": "上传失败,图片非jpg,png,jpeg,gif,请重新上传!", }) return } else if file.Size/1024 > 2000 { log.Println("上传图片大于2M,请重新上传") c.JSON(http.StatusBadRequest, gin.H{ "msg": "上传图片大于2M,请重新上传", }) return } else { f, err := file.Open() if err != nil { log.Println(err) c.JSON(http.StatusBadRequest, gin.H{ "msg": "上传失败,打开文件失败!", "ERROR-CONTROLLER": err, }) } defer f.Close() result := util.Upload(file.Filename, f) if result == "" { c.JSON(http.StatusBadRequest, gin.H{ "msg": "上传失败", }) return } c.JSON(http.StatusOK, gin.H{ "msg": "上传成功!", "result": result, }) } } // Delete // @Summary Delete // @Description 腾讯云删除图片 // @Accept json // @Produce json // @Author hyy 2022-03-03 19:30:37 // @Param fileName path string true "想要删除的文件名" // @Router /v1/tencentCos/{fileName} [DELETE] func Delete(c *gin.Context) { fileName := c.Param("fileName") if util.Delete(fileName) { c.JSON(http.StatusOK, gin.H{ "msg": "删除成功", "result": true, }) return } else { c.JSON(http.StatusBadRequest, gin.H{ "msg": "删除失败", "result": false, }) return } }
4. 测试代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>腾讯云图片测试</title> </head> <body> <form action="http://localhost:8000/v1/tencentCos" method="post" enctype="multipart/form-data"> 上传文件:<input type="file" name="file"> <input type="submit" value="提交"> </form> </body> </html>