From e09294d38854fd69c4e122c2229d0c94c3ea9678 Mon Sep 17 00:00:00 2001 From: HFO4 <912394456@qq.com> Date: Wed, 20 Nov 2019 15:24:26 +0800 Subject: [PATCH] Feat: insert file record to database --- models/file.go | 8 ++++++++ pkg/filesystem/filesystem.go | 22 ++++++++++++++++++++-- pkg/filesystem/hooks.go | 4 +++- pkg/util/logger.go | 5 ++++- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/models/file.go b/models/file.go index 0a30966..05ce596 100644 --- a/models/file.go +++ b/models/file.go @@ -16,6 +16,14 @@ type File struct { Dir string `gorm:"size:65536"` } +// Create 创建文件记录 +func (file *File) Create() (uint, error) { + if err := DB.Create(file).Error; err != nil { + return 0, err + } + return file.ID, nil +} + // GetFileByPathAndName 给定路径、文件名、用户ID,查找文件 func GetFileByPathAndName(path string, name string, uid uint) (File, error) { var file File diff --git a/pkg/filesystem/filesystem.go b/pkg/filesystem/filesystem.go index e3cb67f..6049adb 100644 --- a/pkg/filesystem/filesystem.go +++ b/pkg/filesystem/filesystem.go @@ -79,8 +79,26 @@ func NewFileSystem(user *model.User) (*FileSystem, error) { */ // AddFile 新增文件记录 -func (fs *FileSystem) AddFile(parent *model.Folder) error { - return nil +func (fs *FileSystem) AddFile(ctx context.Context, parent *model.Folder) (*model.File, error) { + file := ctx.Value(FileHeaderCtx).(FileHeader) + filePath := ctx.Value(SavePathCtx).(string) + + newFile := model.File{ + Name: file.GetFileName(), + SourceName: filePath, + UserID: fs.User.ID, + Size: file.GetSize(), + FolderID: parent.ID, + PolicyID: fs.User.Policy.ID, + Dir: parent.PositionAbsolute, + } + _, err := newFile.Create() + + if err != nil { + return nil, err + } + + return &newFile, nil } /* ================ diff --git a/pkg/filesystem/hooks.go b/pkg/filesystem/hooks.go index 3d4d3a6..105da3c 100644 --- a/pkg/filesystem/hooks.go +++ b/pkg/filesystem/hooks.go @@ -73,10 +73,12 @@ func GenericAfterUpload(ctx context.Context, fs *FileSystem) error { } // 向数据库中插入记录 - err := fs.AddFile(&folder) + _, err := fs.AddFile(ctx, &folder) if err != nil { return errors.New("无法插入文件记录") } + // 异步尝试生成缩略图 + return nil } diff --git a/pkg/util/logger.go b/pkg/util/logger.go index 4d80a50..da05d9b 100644 --- a/pkg/util/logger.go +++ b/pkg/util/logger.go @@ -35,8 +35,11 @@ var colors = map[string]func(a ...interface{}) string{ // Println 打印 func (ll *Logger) Println(prefix string, msg string) { + // TODO Release时去掉 + color.NoColor = false + c := color.New() - _, _ = c.Printf("%s %s %s\n", colors[prefix]("["+prefix+"]"), time.Now().Format("2006-01-02 15:04:05 -0700"), msg) + _, _ = c.Printf("%s %s %s\n", colors[prefix]("["+prefix+"]"), time.Now().Format("2006-01-02 15:04:05"), msg) } // Panic 极端错误