一、腾讯云对象存储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,
RequestBody: false,
ResponseHeader: true,
ResponseBody: true,
Writer: f,
},
},
})
return c
}
func logStatus(err error) bool {
if err == nil {
return true
}
if cos.IsNotFoundError(err) {
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
} else {
logs.Warn(fmt.Sprintf("ERROR: %v\n", err))
return false
}
}
func Upload(fileName string,file io.Reader) bool {
c := getCos()
_, err := c.Object.Put(context.Background(),fileName,file,nil)
return logStatus(err)
}
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
}
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 {
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()
}
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
}
}
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>
|