diff --git a/dao/file.go b/dao/file.go index 058a832..96e4428 100644 --- a/dao/file.go +++ b/dao/file.go @@ -1,6 +1,9 @@ package dao -import "gorm.io/gorm" +import ( + "gorm.io/gorm" + "videoplayer/proto" +) type File struct { gorm.Model @@ -12,6 +15,7 @@ type File struct { FileType string `gorm:"column:file_type"` FilePath string `gorm:"column:file_path"` AuthID int `gorm:"column:auth_id"` + Md5 string `gorm:"column:md5;type:varchar(255);uniqueIndex:idx_file_name"` } func CreateFile(fileStoreName, fileName, fileType, filePath string, fileSize, authID int, NeedAuth bool) uint { @@ -82,3 +86,13 @@ func DeleteFileById(id int) bool { } return true } + +func FindFileByMd5(md5 string) File { + var file File + if proto.Config.SERVER_SQL_LOG { + DB.Debug().Where("md5 = ?", md5).First(&file) + } else { + DB.Where("md5 = ?", md5).First(&file) + } + return file +} diff --git a/handler/tool.go b/handler/tool.go index c6f85d6..9b75745 100644 --- a/handler/tool.go +++ b/handler/tool.go @@ -142,6 +142,20 @@ func UploadFile(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"error": "upload file failed", "code": proto.UploadFileFailed, "message": "failed"}) return } + //计算文件md5值 + file_, _ := file.Open() + md5Value := service.CalculateFileMd5(file_) + if md5Value == "" { + c.JSON(http.StatusOK, gin.H{"error": "计算文件MD5值失败", "code": proto.UploadFileFailed, "message": "failed"}) + return + } + //查询文件是否已存在 + fileExist := dao.FindFileByMd5(md5Value) + if fileExist.ID != 0 { + fileExist.FilePath = "" + c.JSON(http.StatusOK, gin.H{"code": proto.SuccessCode, "message": "success", "data": fileExist}) + return + } //保存文件 filePath, fileStoreName, err := service.SaveFile(c, file, uploadType) diff --git a/service/fileService.go b/service/fileService.go index 00ca429..ee75bd6 100644 --- a/service/fileService.go +++ b/service/fileService.go @@ -1,8 +1,11 @@ package service import ( + "crypto/md5" + "fmt" "github.com/gin-gonic/gin" "github.com/google/uuid" + "io" "mime/multipart" "os" "path" @@ -34,7 +37,6 @@ func SaveFile(c *gin.Context, file *multipart.FileHeader, uploadType string) (st //生成文件路径 path_ := getFilePath(proto.FILE_BASE_DIR) filePath := path_ + "/" + fileStoreName - //保存文件 if err := c.SaveUploadedFile(file, filePath); err != nil { return "", "", err @@ -45,3 +47,11 @@ func SaveFile(c *gin.Context, file *multipart.FileHeader, uploadType string) (st return path_, fileStoreName, nil } + +func CalculateFileMd5(file io.Reader) string { + hash := md5.New() + if _, err := io.Copy(hash, file); err != nil { + return "" + } + return fmt.Sprintf("%x", hash.Sum(nil)) +}