任务一完成
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"mime/multipart"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrFileEmpty = errors.New("文件为空")
|
||||
ErrFileTooLarge = errors.New("文件过大")
|
||||
ErrFileTypeError = errors.New("文件类型不允许")
|
||||
)
|
||||
|
||||
// OSS 对象存储接口
|
||||
type OSS interface {
|
||||
Upload(file *multipart.FileHeader) (string, string, error)
|
||||
Delete(key string) error
|
||||
}
|
||||
|
||||
// Config 上传配置
|
||||
type Config struct {
|
||||
Type string // local, aliyun, tencent, qiniu, minio, aws-s3, huawei-obs, cloudflare-r2
|
||||
Path string
|
||||
MaxSize int64
|
||||
}
|
||||
|
||||
// GenerateFileName 生成文件名
|
||||
func GenerateFileName(originalName string) string {
|
||||
ext := path.Ext(originalName)
|
||||
name := uuid.New().String()
|
||||
return name + ext
|
||||
}
|
||||
|
||||
// GeneratePath 生成存储路径
|
||||
func GeneratePath(basePath string) string {
|
||||
now := time.Now()
|
||||
return path.Join(basePath, now.Format("2006/01/02"))
|
||||
}
|
||||
|
||||
// CheckFileSize 检查文件大小
|
||||
func CheckFileSize(size int64, maxSize int64) error {
|
||||
if size > maxSize {
|
||||
return ErrFileTooLarge
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CheckFileType 检查文件类型
|
||||
func CheckFileType(filename string, allowTypes []string) error {
|
||||
ext := strings.ToLower(path.Ext(filename))
|
||||
for _, t := range allowTypes {
|
||||
if ext == t || t == "*" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return ErrFileTypeError
|
||||
}
|
||||
|
||||
// DefaultAllowTypes 默认允许的文件类型
|
||||
var DefaultAllowTypes = []string{
|
||||
".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp",
|
||||
".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx",
|
||||
".txt", ".md", ".json", ".xml", ".csv",
|
||||
".zip", ".rar", ".7z", ".tar", ".gz",
|
||||
".mp3", ".mp4", ".avi", ".mov", ".wmv",
|
||||
}
|
||||
Reference in New Issue
Block a user