0%

腾讯COS公有云-golang上传-下载

使用腾讯公有云COS

安装SDK,访问官网对象存储 快速入门-SDK 文档-文档中心-腾讯云 (tencent.com)

  1. 创建COS连接客户端
package cos

import (
	"github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
	"storage-cloud/config"
)
var cosCli *cos.Client
// Client : 创建oss client对象
func Client() *cos.Client {
	if cosCli != nil {
		return cosCli
	}
    //https://console.cloud.tencent.com/cos5/bucket, 关于地域的详情见 https://cloud.tencent.com/document/product/436/6224
	u, _ := url.Parse(config.BucketURL)
	// 用于Get Service 查询,默认全地域 service.cos.myqcloud.com
	su, _ := url.Parse(config.ServiceURL)
	b := &cos.BaseURL{BucketURL: u, ServiceURL: su}
	// 1.永久密钥
	cosCli = cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  config.SECRETID,  // 替换为用户的 SecretId,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
			SecretKey: config.SecretKey, // 替换为用户的 SecretKey,请登录访问管理控制台进行查看和管理,https://console.cloud.tencent.com/cam/capi
		},
	})
	return cosCli
}
  1. 上传示例(使用预签名URL上传)

使用该方法主要为了添加Header,使上传文件包含文件类型元信息,促使下载时能直接下载为该类型文件

//腾讯云COS上传
		c := cos.Client()
		cosPath := COSLocation + fileMeta.FileSha1
		// 1. 获取预签名URL 
		presignedURL, err := c.Object.GetPresignedURL(context.Background(), http.MethodPut, cosPath, config.SECRETID, config.SecretKey, time.Hour, nil)
		if err != nil {
			panic(err)
		}
		// 2. 通过预签名方式上传对象
		req, err := http.NewRequest(http.MethodPut, presignedURL.String(), newFile)
		if err != nil {
			panic(err)
		}
		//head为 file, head, err := r.FormFile("file") http上传文件的元信息
		contentType := head.Header.Get("Content-Type")
		// 用户可自行设置请求头部
		req.Header.Set("Content-Type", contentType)
		//使浏览器不自动预览
		req.Header.Set("Content-Disposition", "attachment")
		_, err = http.DefaultClient.Do(req)
		if err != nil {
			panic(err)
		}
  1. 下载接口(使用预签名URL下载)

方便直接通过URL浏览器下载

也可使用官网其他方法对象存储 下载对象-SDK 文档-文档中心-腾讯云 (tencent.com)

如果需要通过浏览器下载,也可如下:

示例

// 1. 从响应体中获取对象
resp, err := client.Object.Get(context.Background(), key, opt)
if err != nil {
     panic(err)
}
data, err:=ioutil.ReadAll(resp.Body)
//识别http浏览器响应头 让浏览器识别出是文件下载
w.Header().Set(FileTypeHeader, FileTypeHeaderValue)
w.Header().Set(FileDisHeader, FileDisHeaderValue+<你文件的名称:FileName>+"\"")
w.Write(data)

预签名URL方法:

// 1.获取对象访问 URL
cosPath := row.FileAddr.String
c := cos.Client()
// 获取预签名URL
presignedURL, err := c.Object.GetPresignedURL(context.Background(), http.MethodGet, cosPath, config.SECRETID, config.SecretKey, time.Hour, nil)
if err != nil {
	panic(err)
}
//通过预签名URL下载对象
w.Write([]byte(presignedURL.String()))
-------------本文结束感谢您的阅读-------------
打赏一瓶矿泉水