当前位置:网站首页>Beego learning - Tencent cloud upload pictures
Beego learning - Tencent cloud upload pictures
2022-07-03 09:15:00 【Fill your head with water】
Catalog
One 、 Tencent cloud object storage COS
1. Create bucket
Then go straight to the next step - create .
2. API Key creation
3. See what you need in your code
Bucket name Bucket、 The region Region
secret key
APPID
、SecretId
、SecretKey
Two 、 Code
1. The configuration file app.conf
Write the above values to the corresponding location of the configuration file
# TencentCloud Tencent cloud
# Bucket name
COS_BUCKET_NAME = ""
# The region
COS_REGION = ""
# secret key :APPID
COS_APP_ID = ""
# secret key :SecretId
COS_SECRET_ID = ""
# secret key :SecretKey
COS_SECRET_KEY = ""
# This item is fixed
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 " Upload files "
// @Param filesPath string " The file path you want to upload Such as :./images/xx.png"
// @return bool " Whether the upload is successful "
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 " Download the file "
@Param fileName string " The file name you want to download Such as :xx.png"
@Param fileSavePath string " Save to local path , Such as :./image"
@return bool " Whether the download was successful "
//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 " Delete file "
// @Param fileName string " The file name you want to delete Such as :xx.png"
// @return bool " Delete successful "
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 Upload files to Tencent cloud
// @Param files form true " File you want to upload "
// @router /upload [post]
func (t *TenCloudCosController) Upload() {
files, err := t.GetFiles("files")
if err != nil {
logs.Warn(err)
t.Data["json"] = models.GetRevaErr(err, " Upload failed ")
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(" Uploading pictures is not jpg,png,jpeg,gif, Please upload again !")
t.Data["json"] = models.GetRevaErr(nil, " Uploading pictures is not jpg,png,jpeg,gif, Please upload again !")
t.ServeJSON()
return
} else if file.Size/1024 > 2000 {
logs.Warn(" The uploaded image is larger than 2M, Please upload again ")
t.Data["json"] = models.GetRevaErr(nil, " The uploaded image is larger than 2M, Please upload again !")
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(" Upload failed !")
t.ServeJSON()
return
}
}
}
t.Data["json"] = models.GetRevaOk(" Upload successful !")
t.ServeJSON()
}
// DeleteFile
// @Title DeleteFile
// @Description Delete files from Tencent cloud
// @Param fileName path string true " Name of the file you want to delete "
// @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(" Delete successful !")
t.ServeJSON()
return
}else {
t.Data["json"]=models.GetRevaOk(" Delete failed !")
t.ServeJSON()
return
}
}else {
t.Data["json"]=models.GetRevaOk(" Delete failed , The file name cannot be empty !")
t.ServeJSON()
return
}
}
Download
@Title Download
@Description Download pictures from Tencent cloud
@Param fileName path string true " Name of the file you want to download "
@Param fileSavePath path string true " The path you want to save "
@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(" Download successful !")
// t.ServeJSON()
// return
// }else {
// t.Data["json"]=models.GetRevaErr(nil," Download failed , file name / The save path cannot be empty !")
// t.ServeJSON()
// return
// }
//}
4. test test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Test Tencent cloud multi image upload </title>
</head>
<body>
<form action="http://localhost:8081/api/tencentcloud/upload" method="post" enctype="multipart/form-data">
Upload files :<input type="file" name="files" multiple="multiple">
<input type="submit" value=" Submit ">
</form>
</body>
</html>
边栏推荐
- Low code momentum, this information management system development artifact, you deserve it!
- Using DLV to analyze the high CPU consumption of golang process
- Gaussian elimination acwing 883 Gauss elimination for solving linear equations
- 推荐一个 yyds 的低代码开源项目
- LeetCode 75. 颜色分类
- Solve POM in idea Comment top line problem in XML file
- LeetCode 30. Concatenate substrings of all words
- Complex character + number pyramid
- AcWing 786. 第k个数
- Tree DP acwing 285 A dance without a boss
猜你喜欢
[point cloud processing paper crazy reading frontier version 10] - mvtn: multi view transformation network for 3D shape recognition
LeetCode 57. Insert interval
LeetCode 438. 找到字符串中所有字母异位词
LeetCode 513. 找树左下角的值
拯救剧荒,程序员最爱看的高分美剧TOP10
LeetCode 515. Find the maximum value in each tree row
Solve POM in idea Comment top line problem in XML file
LeetCode 715. Range 模块
[point cloud processing paper crazy reading classic version 11] - mining point cloud local structures by kernel correlation and graph pooling
【点云处理之论文狂读经典版9】—— Pointwise Convolutional Neural Networks
随机推荐
LeetCode 1089. 复写零
Complex character + number pyramid
Solve POM in idea Comment top line problem in XML file
常见渗透测试靶场
LeetCode 508. 出现次数最多的子树元素和
Discussion on enterprise informatization construction
[point cloud processing paper crazy reading classic version 14] - dynamic graph CNN for learning on point clouds
Jenkins learning (I) -- Jenkins installation
2022-2-14 learning xiangniuke project - Session Management
推荐一个 yyds 的低代码开源项目
LeetCode 715. Range 模块
LeetCode 75. Color classification
The "booster" of traditional office mode, Building OA office system, was so simple!
<, < <,>, > > Introduction in shell
Summary of methods for counting the number of file lines in shell scripts
剑指 Offer II 091. 粉刷房子
2022-2-14 learning the imitation Niuke project - send email
Beego learning - JWT realizes user login and registration
AcWing 786. Number k
[point cloud processing paper crazy reading cutting-edge version 12] - adaptive graph revolution for point cloud analysis