Lee-WineList/utils/oss.go
2023-04-24 17:19:41 +08:00

63 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import (
"Lee-WineList/config"
"fmt"
"git.echol.cn/loser/logger/log"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"io"
)
type ossUtils struct{}
func OssUtils() *ossUtils {
return &ossUtils{}
}
// UploadReader 上传文件 - io.Reader
func (o ossUtils) UploadReader(fileName string, data io.Reader) (string, error) {
// 创建OSSClient实例。
client, err := oss.New(config.Scd.Aliyun.Oss.Endpoint, config.Scd.Aliyun.Oss.AccessKeyId, config.Scd.Aliyun.Oss.AccessKeySecret)
if err != nil {
log.Errorf("创建OSSClient实例失败: %s", err)
return "", err
}
// 获取存储空间。
bucket, err := client.Bucket(config.Scd.Aliyun.Oss.Bucket)
if err != nil {
log.Errorf("获取存储空间失败: %s", err)
return "", err
}
// 指定存储类型为标准存储,默认为标准存储。
storageType := oss.ObjectStorageClass(oss.StorageStandard)
// 指定访问权限为公共读默认为继承bucket的权限。
objectAcl := oss.ObjectACL(oss.ACLPublicRead)
// 上传文件
err = bucket.PutObject(fileName, data, storageType, objectAcl)
if err != nil {
log.Errorf("上传文件失败: %s", err)
return "", err
}
fileUrl := fmt.Sprintf("https://%s.%s/%s", config.Scd.Aliyun.Oss.Bucket, config.Scd.Aliyun.Oss.Endpoint, fileName)
return fileUrl, err
}
func (o ossUtils) GetFile(fileName, localFilePath string) error {
client, err := oss.New(config.Scd.Aliyun.Oss.Endpoint, config.Scd.Aliyun.Oss.AccessKeyId, config.Scd.Aliyun.Oss.AccessKeySecret)
if err != nil {
log.Errorf("创建OSSClient实例失败: %s", err)
return err
}
// 获取存储空间。
bucket, err := client.Bucket(config.Scd.Aliyun.Oss.Bucket)
if err != nil {
log.Errorf("获取存储空间失败: %s", err)
return err
}
err = bucket.GetObjectToFile(fileName, localFilePath)
if err != nil {
return err
}
return nil
}