zhangqian
2023-08-26 5193dcb9336e853502baf8a539d3f45efebe2f86
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package example
 
import (
    "errors"
 
    "gorm.io/gorm"
    "srm/global"
    "srm/model/example"
)
 
type FileUploadAndDownloadService struct{}
 
//@author: [piexlmax](https://github.com/piexlmax)
//@function: FindOrCreateFile
//@description: 上传文件时检测当前文件属性,如果没有文件则创建,有则返回文件的当前切片
//@param: fileMd5 string, fileName string, chunkTotal int
//@return: file model.ExaFile, err error
 
func (e *FileUploadAndDownloadService) FindOrCreateFile(fileMd5 string, fileName string, chunkTotal int) (file example.ExaFile, err error) {
    var cfile example.ExaFile
    cfile.FileMd5 = fileMd5
    cfile.FileName = fileName
    cfile.ChunkTotal = chunkTotal
 
    if errors.Is(global.GVA_DB.Where("file_md5 = ? AND is_finish = ?", fileMd5, true).First(&file).Error, gorm.ErrRecordNotFound) {
        err = global.GVA_DB.Where("file_md5 = ? AND file_name = ?", fileMd5, fileName).Preload("ExaFileChunk").FirstOrCreate(&file, cfile).Error
        return file, err
    }
    cfile.IsFinish = true
    cfile.FilePath = file.FilePath
    err = global.GVA_DB.Create(&cfile).Error
    return cfile, err
}
 
//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateFileChunk
//@description: 创建文件切片记录
//@param: id uint, fileChunkPath string, fileChunkNumber int
//@return: error
 
func (e *FileUploadAndDownloadService) CreateFileChunk(id uint, fileChunkPath string, fileChunkNumber int) error {
    var chunk example.ExaFileChunk
    chunk.FileChunkPath = fileChunkPath
    chunk.ExaFileID = id
    chunk.FileChunkNumber = fileChunkNumber
    err := global.GVA_DB.Create(&chunk).Error
    return err
}
 
//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteFileChunk
//@description: 删除文件切片记录
//@param: fileMd5 string, fileName string, filePath string
//@return: error
 
func (e *FileUploadAndDownloadService) DeleteFileChunk(fileMd5 string, filePath string) error {
    var chunks []example.ExaFileChunk
    var file example.ExaFile
    err := global.GVA_DB.Where("file_md5 = ? ", fileMd5).First(&file).
        Updates(map[string]interface{}{
            "IsFinish":  true,
            "file_path": filePath,
        }).Error
    if err != nil {
        return err
    }
    err = global.GVA_DB.Where("exa_file_id = ?", file.ID).Delete(&chunks).Unscoped().Error
    return err
}