任务一完成
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path"
|
||||
)
|
||||
|
||||
// Local 本地存储
|
||||
type Local struct {
|
||||
StorePath string
|
||||
BasePath string
|
||||
}
|
||||
|
||||
// NewLocal 创建本地存储
|
||||
func NewLocal(storePath, basePath string) *Local {
|
||||
return &Local{
|
||||
StorePath: storePath,
|
||||
BasePath: basePath,
|
||||
}
|
||||
}
|
||||
|
||||
// Upload 上传文件
|
||||
func (l *Local) Upload(file *multipart.FileHeader) (string, string, error) {
|
||||
// 生成文件名和路径
|
||||
fileName := GenerateFileName(file.Filename)
|
||||
filePath := GeneratePath(l.BasePath)
|
||||
fullPath := path.Join(l.StorePath, filePath)
|
||||
|
||||
// 创建目录
|
||||
if err := os.MkdirAll(fullPath, os.ModePerm); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
// 打开源文件
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
// 创建目标文件
|
||||
dstPath := path.Join(fullPath, fileName)
|
||||
dst, err := os.Create(dstPath)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
// 复制文件
|
||||
if _, err = io.Copy(dst, src); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
// 返回访问路径和存储key
|
||||
accessPath := path.Join("/", filePath, fileName)
|
||||
key := path.Join(filePath, fileName)
|
||||
return accessPath, key, nil
|
||||
}
|
||||
|
||||
// Delete 删除文件
|
||||
func (l *Local) Delete(key string) error {
|
||||
fullPath := path.Join(l.StorePath, key)
|
||||
return os.Remove(fullPath)
|
||||
}
|
||||
Reference in New Issue
Block a user