一、腾讯云对象存储COS
1. 创建储存桶
然后直接下一步-创建即可。
2. API密钥创建
3. 查看代码中需要的东西
- 储存桶名称Bucket、所属地域Region
- 密钥
APPID
、SecretId
、SecretKey
二、代码
1. 配置文件 app.conf
将上面查看的几个值写入配置文件对应位置即可
# 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
import ( "context" "fmt" "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "github.com/tencentyun/cos-go-sdk-v5" "github.com/tencentyun/cos-go-sdk-v5/debug" "io" "net/http" "net/url" "os" ) func getCos() *cos.Client { f, _ := os.OpenFile("./log.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) u, _ := url.Parse(fmt.Sprintf( beego.AppConfig.String("COS_URL_FORMAT"), beego.AppConfig.String("COS_BUCKET_NAME"), beego.AppConfig.String("COS_APP_ID"), beego.AppConfig.String("COS_REGION"), )) b := &cos.BaseURL{BucketURL: u} c := cos.NewClient(b, &http.Client{ Transport: &cos.AuthorizationTransport{ SecretID: beego.AppConfig.String("COS_SECRET_ID"), SecretKey: beego.AppConfig.String("COS_SECRET_KEY"), Transport: &debug.DebugRequestTransport{ RequestHeader: true, // Notice when put a large file and set need the request body, might happend out of memory error. RequestBody: false, ResponseHeader: true, ResponseBody: true, Writer: f, }, }, }) return c } func logStatus(err error) bool { if err == nil { return true } if cos.IsNotFoundError(err) { // WARN logs.Warn("WARN: Resource is not existed") return false } else if e, ok := cos.IsCOSError(err); ok { logs.Warn(fmt.Sprintf("ERROR: Code: %v\n", e.Code)) logs.Warn(fmt.Sprintf("ERROR: Message: %v\n", e.Message)) logs.Warn(fmt.Sprintf("ERROR: Resource: %v\n", e.Resource)) logs.Warn(fmt.Sprintf("ERROR: RequestID: %v\n", e.RequestID)) return false // ERROR } else { logs.Warn(fmt.Sprintf("ERROR: %v\n", err)) return false // ERROR } } // Upload // @Title Upload // @Description "上传文件" // @Param filesPath string "想要上传的文件路径 如:./images/xx.png" // @return bool "上传是否成功" func Upload(fileName string,file io.Reader) bool { c := getCos() _, err := c.Object.Put(context.Background(),fileName,file,nil) return logStatus(err) } DownLoad @Title DownLoad @Description "下载文件" @Param fileName string "想要下载的文件名 如:xx.png" @Param fileSavePath string "保存到本地的路径,如:./image" @return bool "下载是否成功" //func DownLoad(fileName string, fileSavePath string) bool { // c := getCos() // _, err := c.Object.GetToFile(context.Background(), fileName, fileSavePath+"/recv_"+fileName, nil) // return logStatus(err) //} // 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 logStatus(err) }
3.
controller/tencent_cloud_cos_controller.go
type TenCloudCosController struct { beego.Controller } // Upload // @Title Upload // @Description 上传文件到腾讯云 // @Param files form true "想要上传的文件" // @router /upload [post] func (t *TenCloudCosController) Upload() { files, err := t.GetFiles("files") if err != nil { logs.Warn(err) t.Data["json"] = models.GetRevaErr(err, "上传失败") t.ServeJSON() return } for _, file := range files { imgType := file.Header["Content-Type"][0] if imgType != "image/png" && imgType != "image/jpg" && imgType != "image/jpeg" && imgType != "image/gif" { logs.Warn("上传图片非jpg,png,jpeg,gif,请重新上传!") t.Data["json"] = models.GetRevaErr(nil, "上传图片非jpg,png,jpeg,gif,请重新上传!") t.ServeJSON() return } else if file.Size/1024 > 2000 { logs.Warn("上传图片大于2M,请重新上传") t.Data["json"] = models.GetRevaErr(nil, "上传图片大于2M,请重新上传!") t.ServeJSON() return } else { // *multipart.FileHeader f,err:=file.Open() if err!=nil { logs.Warn("ERROR:",err) return } defer f.Close() if !utils.Upload(file.Filename,f){ t.Data["json"] = models.GetRevaOk("上传失败!") t.ServeJSON() return } } } t.Data["json"] = models.GetRevaOk("上传成功!") t.ServeJSON() } // DeleteFile // @Title DeleteFile // @Description 从腾讯云删除文件 // @Param fileName path string true "想要删除的文件名称" // @router /deleteFile/:fileName [delete] func (t *TenCloudCosController) DeleteFile() { fileName:=t.GetString(":fileName") if fileName!="" { result:=utils.Delete(fileName) if result { t.Data["json"]=models.GetRevaOk("删除成功!") t.ServeJSON() return }else { t.Data["json"]=models.GetRevaOk("删除失败!") t.ServeJSON() return } }else { t.Data["json"]=models.GetRevaOk("删除失败,文件名不可以为空!") t.ServeJSON() return } } Download @Title Download @Description 从腾讯云下载图片 @Param fileName path string true "想要下载的文件名称" @Param fileSavePath path string true "想要保存的路径" @router /download/:fileName/:fileSavePath [post] //func (t *TenCloudCosController) Download() { // fileName:=t.GetString("fileName") // fileSavePath:=t.GetString("fileSavePath") // if fileName!=""&&fileSavePath!="" { // utils.DownLoad(fileName,fileSavePath) // t.Data["json"]=models.GetRevaOk("下载成功!") // t.ServeJSON() // return // }else { // t.Data["json"]=models.GetRevaErr(nil,"下载失败,文件名/保存路径不可为空!") // t.ServeJSON() // return // } //}
4. 测试 test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>测试腾讯云多图片上传</title> </head> <body> <form action="http://localhost:8081/api/tencentcloud/upload" method="post" enctype="multipart/form-data"> 上传文件:<input type="file" name="files" multiple="multiple"> <input type="submit" value="提交"> </form> </body> </html>