10 Commits

Author SHA1 Message Date
coward
97911ec21d :arrow_up:升级uuid依赖 2024-03-07 11:01:37 +08:00
coward
aa203fcf61 :zap:优化 2023-02-27 15:25:33 +08:00
coward
c00770cab3 :arrow_up:升级了oss依赖 2022-09-02 10:07:54 +08:00
coward
386d2db45e '修复冲突' 2021-06-02 19:59:59 +08:00
coward
20fae36533 '修改了方法注释,新增了一个获取临时地址的方法' 2021-06-02 19:57:25 +08:00
coward
605a9f829e '修复顺序' 2021-04-07 18:13:24 +08:00
coward
a794b3d2ff '临时兼容' 2021-04-07 17:33:23 +08:00
coward
d89ca3242c '上传兼容文件[]byte化' 2021-03-16 11:17:11 +08:00
coward
17b7856b9b '去除参数' 2021-03-16 10:30:59 +08:00
coward
cf0e2dc94c '兼容[]byte数组文件上传' 2021-03-16 10:30:34 +08:00
7 changed files with 197 additions and 89 deletions

View File

@@ -5,6 +5,7 @@
对阿里云oss-golang sdk 进行上传、删除的简单封装,便于使用
上传使用字节流,内自带 *os.File | *multipart.FileHeader 文件类型转字节流,
以及使用字符串路径 例如:./test.png 。测试案例oss_test.go中有不同操作的案例
新版兼容文件[]byte化上传
#install
go get github.com/cowardmrx/go_aliyun_oss
@@ -23,8 +24,8 @@ go get github.com/cowardmrx/go_aliyun_oss
ossClient := ossConfig.CreateOssConnect()
//put 方法返回完整的oss 可访问地址
uri := ossClient.Put("logo/","./File/3HaqWaOzJWD86DDvZD9Pmn9VUEOBOBbuWackGOXb (2).jpeg")
//put 方法返回完整的oss 可访问地址 第三个参数 如果文件不是[]byte数组的可以直接传递空如果是[]byte也可以是空会默认给出一个png的文件类型建议实际中给出文件类型
uri := ossClient.Put("logo/","./File/3HaqWaOzJWD86DDvZD9Pmn9VUEOBOBbuWackGOXb (2).jpeg","")
fmt.Println(uri)
//HasExists 方法返回一个bool值 true-存在 false-不存在
@@ -43,6 +44,4 @@ go get github.com/cowardmrx/go_aliyun_oss
})
fmt.Println(isSuccess)
#详细使用方法请参照oss_test.go文件中的示例

67
file.go
View File

@@ -1,8 +1,9 @@
package go_aliyun_oss
import (
"errors"
"fmt"
uuid "github.com/satori/go.uuid"
"github.com/google/uuid"
"io/ioutil"
"mime/multipart"
"os"
@@ -20,28 +21,31 @@ type OssFile struct {
}
type OssFileInterface interface {
FileTypeTransForm() (*OssFile,error)
FileTypeTransForm() (*OssFile, error)
GetFileType() *OssFile
}
// file type transform
//@title 文件类型转换
func (ossFile *OssFile) FileTypeTransForm() (*OssFile,error) {
// FileTypeTransForm file type transform
// @title 文件类型转换
func (ossFile *OssFile) FileTypeTransForm() (*OssFile, error) {
var err error
switch ossFile.File.(type) {
case *os.File:
ossFile.FileByte,err = ioutil.ReadAll(ossFile.File.(*os.File))
ossFile.FileByte, err = ioutil.ReadAll(ossFile.File.(*os.File))
if err != nil {
panic("read os type file failed:" + err.Error())
return nil, errors.New("read os type file failed:" + err.Error())
}
_,ossFile.FileOldName = filepath.Split(ossFile.File.(*os.File).Name())
_, ossFile.FileOldName = filepath.Split(ossFile.File.(*os.File).Name())
break
case *multipart.FileHeader:
fileResources,err := ossFile.File.(*multipart.FileHeader).Open()
fileResources, err := ossFile.File.(*multipart.FileHeader).Open()
if err != nil {
panic("open multipart file failed:" + err.Error())
@@ -49,49 +53,70 @@ func (ossFile *OssFile) FileTypeTransForm() (*OssFile,error) {
defer fileResources.Close()
ossFile.FileByte,err = ioutil.ReadAll(fileResources)
ossFile.FileByte, err = ioutil.ReadAll(fileResources)
if err != nil {
panic("read multipart file failed:" + err.Error())
return nil, errors.New("read multipart file failed:" + err.Error())
}
ossFile.FileOldName = ossFile.File.(*multipart.FileHeader).Filename
break
case string:
newFile,err := os.Open(ossFile.File.(string))
newFile, err := os.Open(ossFile.File.(string))
if err != nil {
panic("open file path failed:" + err.Error())
return nil, errors.New("open file path failed:" + err.Error())
}
defer newFile.Close()
ossFile.FileByte,err = ioutil.ReadAll(newFile)
ossFile.FileByte, err = ioutil.ReadAll(newFile)
_,ossFile.FileOldName = filepath.Split(newFile.Name())
_, ossFile.FileOldName = filepath.Split(newFile.Name())
break
// 支持[]byte数组传递 因为无法解析文件类型 默认直接给出文件类型为.png
case []byte:
ossFile.FileByte = ossFile.File.([]byte)
//判断是否指定了文件的类型 如果没有指定默认为png格式
if ossFile.FileType == "" || len(ossFile.FileType) <= 0 {
ossFile.FileOldName = uuid.NewString() + ".png"
} else {
ossFile.FileOldName = uuid.NewString() + ossFile.FileType
}
break
default:
fmt.Println(reflect.TypeOf(ossFile.File))
panic("file type is not support" )
return nil, errors.New("file type is not support")
}
ossFile.GetFileType()
return ossFile,nil
return ossFile, nil
}
//split file type and generate file name
//截取文件类型
// GetFileType split file type and generate file name
// 截取文件类型
func (ossFile *OssFile) GetFileType() *OssFile {
// 当没有传递文件类型时去文件名中截取出文件类型
if ossFile.FileType == "" || len(ossFile.FileType) <= 0 {
//from oldFileName split file type
fileTypeSufIndex := strings.Index(ossFile.FileOldName,".")
fileTypeSufIndex := strings.Index(ossFile.FileOldName, ".")
fileType := ossFile.FileOldName[fileTypeSufIndex:]
ossFile.FileType = fileType
}
//generate only file name
ossFile.FileNewName = uuid.NewV5(uuid.NewV4(),ossFile.FileOldName).String() + ossFile.FileType
ossFile.FileNewName = uuid.NewString() + ossFile.FileType
return ossFile
}

4
go.mod
View File

@@ -3,9 +3,9 @@ module github.com/cowardmrx/go_aliyun_oss
go 1.15
require (
github.com/aliyun/aliyun-oss-go-sdk v2.1.5+incompatible
github.com/aliyun/aliyun-oss-go-sdk v2.2.5+incompatible
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
github.com/satori/go.uuid v1.2.0
github.com/google/uuid v1.6.0 // indirect
golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
)

4
go.sum
View File

@@ -1,7 +1,11 @@
github.com/aliyun/aliyun-oss-go-sdk v2.1.5+incompatible h1:v5yDfjkRY/kOxu05gkh0/D/2wYxbTFCoTr3JqFI0FLE=
github.com/aliyun/aliyun-oss-go-sdk v2.1.5+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/aliyun/aliyun-oss-go-sdk v2.2.5+incompatible h1:QoRMR0TCctLDqBCMyOu1eXdZyMw3F7uGA9qPn2J4+R8=
github.com/aliyun/aliyun-oss-go-sdk v2.2.5+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8=
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f h1:ZNv7On9kyUzm7fvRZumSyy/IUiSC7AzL0I1jKKtwooA=
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/kr/pretty v0.2.1 h1:Fmg33tUaq4/8ym9TJN1x7sLJnHVwhP33CNkpYV/7rwI=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=

View File

@@ -20,7 +20,7 @@ type AliOssConfigInterface interface {
GetAccessibleUrl() string
}
//check AliOssConfig value is exists
// CheckConfig check AliOssConfig value is exists
func (coon *AliOssConfig) CheckConfig() {
//check endPoint
if coon.EndPoint == "" || len(coon.EndPoint) <= 0 {
@@ -49,7 +49,7 @@ func (coon *AliOssConfig) CheckConfig() {
}
//en: create oss connect client
// CreateOssConnect en: create oss connect client
//创建阿里云oss 链接客户端
func (coon *AliOssConfig) CreateOssConnect() *AliOssClient {
//config check
@@ -82,7 +82,7 @@ func (coon *AliOssConfig) CreateOssConnect() *AliOssClient {
}
}
//get oss accessible url
// GetAccessibleUrl get oss accessible url
//拼接阿里云oss可访问地址
func (coon *AliOssConfig) GetAccessibleUrl() string {
var domain string

View File

@@ -2,6 +2,7 @@ package go_aliyun_oss
import (
"bytes"
"errors"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
@@ -11,23 +12,34 @@ type AliOssClient struct {
Client *oss.Bucket
}
//推送文件到oss
//params: ossDir string `oss dir [要推送到的oss目录]` example: test/20201121/
//params: file interface `upload file resource [文件资源]`
//return string `oss file accessible uri [可访问地址]`
func (client *AliOssClient) Put(ossDir string, file interface{}) string {
type ossResponse struct {
Host string
LongPath string
ShortPath string
FileName string
}
// Put 推送文件到oss
// params: ossDir string `oss dir [要推送到的oss目录]` example: test/20201121/
// params: file interface `upload file resource [文件资源]`
// return string `oss file accessible uri [可访问地址]`
func (client *AliOssClient) Put(ossDir string, file interface{}, fileType string) (*ossResponse, error) {
//file to []byte
//文件转字节流
uploadFile := &OssFile{
File: file,
FileType: fileType,
}
ossFile,err := uploadFile.FileTypeTransForm()
ossFile, err := uploadFile.FileTypeTransForm()
if err != nil {
panic("transfer file failed" + err.Error())
return nil, err
}
// 最终的oss名称
var ossFileName string
//ossPath = oss dir + upload file name
//example: oss dir is diy ==== test/20201121/
//time.Now().Format("20060102")
@@ -37,62 +49,92 @@ func (client *AliOssClient) Put(ossDir string, file interface{}) string {
//judge is use origin file name if false fileName = fileNewName (is a only name) else file init name
if client.OriginalFileName == false {
ossPath = ossDir + ossFile.FileNewName
ossFileName = ossFile.FileNewName
} else {
ossPath = ossDir + ossFile.FileOldName
ossFileName = ossFile.FileOldName
}
//upload file to oss
err = client.Client.PutObject(ossPath,bytes.NewReader(ossFile.FileByte))
err = client.Client.PutObject(ossPath, bytes.NewReader(ossFile.FileByte))
if err != nil {
panic("put file to oss failed:" + err.Error())
return nil, errors.New("put file to oss failed:" + err.Error())
}
return client.Domain + "/" + ossPath
return &ossResponse{
Host: client.Domain,
LongPath: client.Domain + "/" + ossPath,
ShortPath: ossPath,
FileName: ossFileName,
}, nil
}
//校验文件是否已经存在
//check file already exists in oss server
//params: ossFilePath string `file oss path [文件的oss的路径]`
func (client *AliOssClient) HasExists(ossFilePath string) bool {
// HasExists 校验文件是否已经存在
// check file already exists in oss server
// params: ossFilePath string `file oss path [文件的oss的路径]`
func (client *AliOssClient) HasExists(ossFilePath string) (bool, error) {
//oss check fun
isExists,err := client.Client.IsObjectExist(ossFilePath)
isExists, err := client.Client.IsObjectExist(ossFilePath)
if err != nil {
panic("check file in oss is exists failed:" + err.Error())
return false, errors.New("check file in oss is exists failed:" + err.Error())
}
return isExists
return isExists, nil
}
//删除文件-单文件删除
//delete one file in oss
//params ossPath string `file oss path [文件的oss路径]`
//return bool
func (client *AliOssClient) Delete(ossFilePath string) bool {
// Delete 删除文件-单文件删除
// delete one file in oss
// params ossPath string `file oss path [文件的oss路径]`
// return bool
func (client *AliOssClient) Delete(ossFilePath string) (bool, error) {
//oss delete one file fun
err := client.Client.DeleteObject(ossFilePath)
if err != nil {
panic("delete file "+ ossFilePath +" failed:" + err.Error())
return false, errors.New("delete file " + ossFilePath + " failed:" + err.Error())
}
return true
return true, nil
}
//删除文件-多文件删除
//delete more file in oss
//params ossPath []string `file oss path array [文件的oss路径数组]`
//return bool
func (client *AliOssClient) DeleteMore(ossFilePath []string) bool {
// DeleteMore 删除文件-多文件删除
// delete more file in oss
// params ossPath []string `file oss path array [文件的oss路径数组]`
// return bool
func (client *AliOssClient) DeleteMore(ossFilePath []string) (bool, error) {
//oss delete more file fun
_,err := client.Client.DeleteObjects(ossFilePath)
_, err := client.Client.DeleteObjects(ossFilePath)
if err != nil {
panic("delete more file in oss failed:" + err.Error())
return false, errors.New("delete more file in oss failed:" + err.Error())
}
return true
return true, nil
}
// GetTemporaryUrl 获取文件临时地址
// path string 文件路径
// expireInSecond int64 多久后过期 单位: 秒,默认 60
func (client *AliOssClient) GetTemporaryUrl(path string, expireInSecond int64) (string, error) {
var expireTime int64
if expireInSecond <= 0 {
expireTime = 60
} else {
expireTime = expireInSecond
}
signUrl, err := client.Client.SignURL(path, oss.HTTPGet, expireTime)
if err != nil {
return "", errors.New("generate sign url failed:" + err.Error())
}
return signUrl, nil
}

View File

@@ -1,7 +1,9 @@
package go_aliyun_oss
import (
"encoding/base64"
"fmt"
"io/ioutil"
"testing"
)
@@ -15,11 +17,33 @@ func TestPut(t *testing.T) {
client := ossConfig.CreateOssConnect()
uri := client.Put("logo/","./File/3HaqWaOzJWD86DDvZD9Pmn9VUEOBOBbuWackGOXb (2).jpeg")
uri := client.Put("logo/", "./File/3HaqWaOzJWD86DDvZD9Pmn9VUEOBOBbuWackGOXb (2).jpeg", ".png")
fmt.Println(uri)
}
func TestPutBase64(t *testing.T) {
ossConfig := &AliOssConfig{
EndPoint: "",
AccessKeyId: "",
AccessKeySecret: "",
BucketName: "",
}
client := ossConfig.CreateOssConnect()
// 读取base
file, _ := ioutil.ReadFile("./File/3HaqWaOzJWD86DDvZD9Pmn9VUEOBOBbuWackGOXb (2).jpeg")
fileStr := base64.StdEncoding.EncodeToString(file)
bat, _ := base64.StdEncoding.DecodeString(fileStr)
uri := client.Put("logo/", bat, ".png")
//
fmt.Println(uri)
}
func TestExists(t *testing.T) {
ossConfig := &AliOssConfig{
EndPoint: "oss-cn-shenzhen.aliyuncs.com",
@@ -68,3 +92,17 @@ func TestAliOssClient_DeleteMore(t *testing.T) {
fmt.Println(deleteRes)
}
func TestAliOssClient_GetTemporaryUrl(t *testing.T) {
ossConfig := &AliOssConfig{
EndPoint: "https://oss-cn-hangzhou.aliyuncs.com",
AccessKeyId: "",
AccessKeySecret: "",
BucketName: "",
}
client := ossConfig.CreateOssConnect()
singUrl := client.GetTemporaryUrl("", 180)
fmt.Println(singUrl)
}