98 lines
2.0 KiB
Go
98 lines
2.0 KiB
Go
package lib
|
|
|
|
import (
|
|
"SciencesServer/utils"
|
|
"errors"
|
|
"fmt"
|
|
"mime/multipart"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type (
|
|
UploadConfig struct {
|
|
Path string // 根目录,完整目录-更目录+时间
|
|
Ext []string // 文件类型
|
|
Size int64 // 文件大小
|
|
Rename bool // 重命名
|
|
}
|
|
|
|
UploadHandle struct {
|
|
Url string `json:"url"`
|
|
Filepath string `json:"filepath"`
|
|
Filename string `json:"filename"`
|
|
RelativePath string `json:"-"`
|
|
}
|
|
)
|
|
|
|
type (
|
|
Handle func(file *multipart.FileHeader, domain string) (*UploadHandle, error)
|
|
)
|
|
|
|
func (this *UploadConfig) ext(ext string) bool {
|
|
if !utils.InArray(strings.ToLower(ext), this.Ext) {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (this *UploadConfig) size(size int64) bool {
|
|
if size > this.Size {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (this *UploadConfig) Handle() Handle {
|
|
return func(file *multipart.FileHeader, domain string) (handle *UploadHandle, e error) {
|
|
ext := filepath.Ext(file.Filename)
|
|
|
|
if !this.ext(strings.Replace(ext, ".", "", 1)) {
|
|
return nil, errors.New("文件类型限制不可上传")
|
|
}
|
|
|
|
if this.Size > 0 && !this.size(file.Size) {
|
|
return nil, errors.New("文件过大不可上传")
|
|
}
|
|
// 判断目录是否存在
|
|
now := time.Now()
|
|
|
|
this.Path += now.Format("20060102") + "/"
|
|
|
|
isExist, err := utils.PathExists(this.Path)
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !isExist {
|
|
if err = utils.MkdirAll(this.Path); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
_file := file.Filename
|
|
|
|
if this.Rename {
|
|
file.Filename = utils.Md5String(file.Filename, fmt.Sprintf("%d", now.UnixNano()))
|
|
_file = file.Filename + ext
|
|
}
|
|
_filepath := "/" + this.Path + _file
|
|
|
|
return &UploadHandle{
|
|
Url: domain + _filepath,
|
|
Filepath: _filepath,
|
|
Filename: _file,
|
|
RelativePath: this.Path + _file,
|
|
}, nil
|
|
}
|
|
}
|
|
|
|
func Upload(path string, ext []string, size int64, rename bool) *UploadConfig {
|
|
return &UploadConfig{
|
|
Path: path,
|
|
Ext: ext,
|
|
Size: size,
|
|
Rename: rename,
|
|
}
|
|
}
|