任务一完成

This commit is contained in:
Yvan
2026-01-07 10:13:35 +08:00
parent e8f8c2819a
commit 35ab7c0b70
24 changed files with 3397 additions and 160 deletions
+82
View File
@@ -0,0 +1,82 @@
package upload
import (
"mime/multipart"
"path"
"github.com/huaweicloud/huaweicloud-sdk-go-obs/obs"
)
// HuaweiObs 华为云OBS
type HuaweiObs struct {
Path string
Bucket string
Endpoint string
AccessKey string
SecretKey string
}
// NewHuaweiObs 创建华为云OBS
func NewHuaweiObs(obsPath, bucket, endpoint, accessKey, secretKey string) *HuaweiObs {
return &HuaweiObs{
Path: obsPath,
Bucket: bucket,
Endpoint: endpoint,
AccessKey: accessKey,
SecretKey: secretKey,
}
}
func (h *HuaweiObs) getClient() (*obs.ObsClient, error) {
return obs.New(h.AccessKey, h.SecretKey, h.Endpoint)
}
// Upload 上传文件
func (h *HuaweiObs) Upload(file *multipart.FileHeader) (string, string, error) {
client, err := h.getClient()
if err != nil {
return "", "", err
}
defer client.Close()
// 生成文件名和路径
fileName := GenerateFileName(file.Filename)
filePath := GeneratePath(h.Path)
key := path.Join(filePath, fileName)
// 打开文件
src, err := file.Open()
if err != nil {
return "", "", err
}
defer src.Close()
// 上传
input := &obs.PutObjectInput{}
input.Bucket = h.Bucket
input.Key = key
input.Body = src
_, err = client.PutObject(input)
if err != nil {
return "", "", err
}
// 返回访问URL和key
accessURL := "https://" + h.Bucket + "." + h.Endpoint + "/" + key
return accessURL, key, nil
}
// Delete 删除文件
func (h *HuaweiObs) Delete(key string) error {
client, err := h.getClient()
if err != nil {
return err
}
defer client.Close()
input := &obs.DeleteObjectInput{}
input.Bucket = h.Bucket
input.Key = key
_, err = client.DeleteObject(input)
return err
}