当前位置:网站首页>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>
边栏推荐
- 传统办公模式的“助推器”,搭建OA办公系统,原来就这么简单!
- How to check whether the disk is in guid format (GPT) or MBR format? Judge whether UEFI mode starts or legacy mode starts?
- Just graduate student reading thesis
- State compression DP acwing 91 Shortest Hamilton path
- State compression DP acwing 291 Mondrian's dream
- LeetCode 535. Encryption and decryption of tinyurl
- LeetCode 515. 在每个树行中找最大值
- LeetCode 532. K-diff number pairs in array
- 低代码前景可期,JNPF灵活易用,用智能定义新型办公模式
- What is an excellent fast development framework like?
猜你喜欢
[point cloud processing paper crazy reading frontier version 10] - mvtn: multi view transformation network for 3D shape recognition
AcWing 786. Number k
【点云处理之论文狂读经典版8】—— O-CNN: Octree-based Convolutional Neural Networks for 3D Shape Analysis
On a un nom en commun, maître XX.
[point cloud processing paper crazy reading classic version 13] - adaptive graph revolutionary neural networks
LeetCode 75. 颜色分类
数字化转型中,企业设备管理会出现什么问题?JNPF或将是“最优解”
【点云处理之论文狂读经典版11】—— Mining Point Cloud Local Structures by Kernel Correlation and Graph Pooling
精彩回顾|I/O Extended 2022 活动干货分享
On February 14, 2022, learn the imitation Niuke project - develop the registration function
随机推荐
剑指 Offer II 091. 粉刷房子
Binary tree sorting (C language, char type)
Methods of using arrays as function parameters in shell
LeetCode 513. 找树左下角的值
LeetCode 57. Insert interval
【点云处理之论文狂读前沿版10】—— MVTN: Multi-View Transformation Network for 3D Shape Recognition
Jenkins learning (III) -- setting scheduled tasks
[point cloud processing paper crazy reading frontier version 10] - mvtn: multi view transformation network for 3D shape recognition
What are the stages of traditional enterprise digital transformation?
What is an excellent fast development framework like?
Too many open files solution
LeetCode 438. 找到字符串中所有字母异位词
LeetCode 324. 摆动排序 II
The difference between if -n and -z in shell
Arbre DP acwing 285. Un bal sans patron.
Character pyramid
How to check whether the disk is in guid format (GPT) or MBR format? Judge whether UEFI mode starts or legacy mode starts?
AcWing 787. 归并排序(模板)
DOM render mount patch responsive system
干货!零售业智能化管理会遇到哪些问题?看懂这篇文章就够了