76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
package storage
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"mime/multipart"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"dianshang/internal/config"
|
|
)
|
|
|
|
// LocalStorage 本地存储服务
|
|
type LocalStorage struct {
|
|
config *config.UploadConfig
|
|
}
|
|
|
|
// NewLocalStorage 创建本地存储服务实例
|
|
func NewLocalStorage(cfg *config.UploadConfig) *LocalStorage {
|
|
return &LocalStorage{
|
|
config: cfg,
|
|
}
|
|
}
|
|
|
|
// UploadFile 上传文件到本地
|
|
func (s *LocalStorage) UploadFile(file multipart.File, filename string, objectPath string) (string, error) {
|
|
// 创建保存路径
|
|
savePath := filepath.Join(s.config.StaticPath, objectPath, filename)
|
|
|
|
// 确保目录存在
|
|
if err := os.MkdirAll(filepath.Dir(savePath), 0755); err != nil {
|
|
return "", fmt.Errorf("创建目录失败: %w", err)
|
|
}
|
|
|
|
// 保存文件
|
|
if err := saveFile(file, savePath); err != nil {
|
|
return "", fmt.Errorf("保存文件失败: %w", err)
|
|
}
|
|
|
|
// 返回文件URL
|
|
fileURL := fmt.Sprintf("%s/%s/%s", s.config.BaseURL, objectPath, filename)
|
|
return fileURL, nil
|
|
}
|
|
|
|
// DeleteFile 删除本地文件
|
|
func (s *LocalStorage) DeleteFile(filePath string) error {
|
|
err := os.Remove(filePath)
|
|
if err != nil {
|
|
return fmt.Errorf("删除本地文件失败: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// IsFileExist 检查文件是否存在
|
|
func (s *LocalStorage) IsFileExist(filePath string) bool {
|
|
_, err := os.Stat(filePath)
|
|
return err == nil
|
|
}
|
|
|
|
// GetFileURL 获取文件访问URL
|
|
func (s *LocalStorage) GetFileURL(objectPath string, filename string) string {
|
|
return fmt.Sprintf("%s/%s/%s", s.config.BaseURL, objectPath, filename)
|
|
}
|
|
|
|
// saveFile 保存上传的文件
|
|
func saveFile(file multipart.File, dst string) error {
|
|
out, err := os.Create(dst)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer out.Close()
|
|
|
|
_, err = io.Copy(out, file)
|
|
return err
|
|
}
|