任务一完成
This commit is contained in:
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user