添加文件存在检测

This commit is contained in:
junleea 2024-12-27 20:27:20 +08:00
parent 381fd3d720
commit 7a650394b0
3 changed files with 40 additions and 2 deletions

View File

@ -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
}

View File

@ -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)

View File

@ -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))
}