Signed-off-by: 吴文峰 <kevin@lmve.net>
This commit is contained in:
2026-01-13 21:08:19 +08:00
parent 3acc19ffd8
commit 0b67a9bf09
16 changed files with 420 additions and 117 deletions
+6 -6
View File
@@ -24,12 +24,12 @@ user:
file:
maxSize: 52428800
pahts:
avatar: "./data/avatar/"
image: "./data/upload/image/"
video: "./data/upload/video/"
music: "./data/upload/music/"
pdf: "./data/upload/pdf/"
other: "./data/upload/other/"
avatar: "data/static/avatar/"
image: "data/upload/image/"
video: "data/upload/video/"
music: "data/upload/music/"
pdf: "data/upload/pdf/"
other: "data/upload/other/"
allowImageMime:
image/jpeg: ".jpeg"
+6 -1
View File
@@ -9,6 +9,11 @@
"userEmailFormatError":-43,
"userCookieError":-44,
"userCookieNotFund":-44,
"userCookieExpired":-44
"userCookieExpired":-44,
"file_mime_err":-51,
"file_size_err":-52,
"file_name_err":-53,
"file_get_err":-54
}
+11
View File
@@ -68,6 +68,17 @@ func main() {
models.ConfigAllInit()
routers.ApiInit()
//创建必要目录
for _, path := range models.ConfigsFile.Pahts {
fmt.Println(path)
err := os.MkdirAll(path, 0755)
if err != nil {
fmt.Printf("创建文件夹失败: %v\n", err)
panic("创建文件夹失败")
}
}
//启动gin服务
r := gin.Default()
-2
View File
@@ -4,8 +4,6 @@ import "github.com/mitchellh/mapstructure"
var Configs map[string]interface{}
//mime信息转换位拓展名
type ConfigsWeb_ struct {
Host string `mapstructure:"host"`
Port string `mapstructure:"port"`
+47 -1
View File
@@ -1,6 +1,13 @@
package models
import "os"
import (
"crypto"
"encoding/hex"
"io"
"mime/multipart"
"net/http"
"os"
)
// 判断文件是否存在
func FileExists(path string) bool {
@@ -10,3 +17,42 @@ func FileExists(path string) bool {
}
return true
}
// 计算文件的哈希
func SHA256HashFile(file_head *multipart.FileHeader) (string, error) {
// 打开文件
file, err := file_head.Open()
if err != nil {
return "foen error", err
}
defer file.Close()
hasher := crypto.SHA256.New()
// 从文件流中读取并计算哈希
_, err = io.Copy(hasher, file)
if err != nil {
return "", err
}
hashBytes := hasher.Sum(nil)
return hex.EncodeToString(hashBytes), nil
}
// 获取文件mime
func GetFileMime(file_head *multipart.FileHeader) (string, error) {
file, err := file_head.Open()
if err != nil {
return "foen error", err
}
defer file.Close()
// 读取前512字节用于MIME检测
buffer := make([]byte, 512)
io.ReadFull(file, buffer)
mimeType := http.DetectContentType(buffer)
return mimeType, nil
}
+1
View File
@@ -50,6 +50,7 @@ func SeparateData(ctx *gin.Context) (map[string]interface{}, string) {
func ApiRoot(r *gin.RouterGroup) {
ApiStatic(r.Group("/static"))
ApiUser(r.Group("/users"))
r.GET("/", func(ctx *gin.Context) {
+25
View File
@@ -0,0 +1,25 @@
package routers
import (
"ops/models"
"path"
"github.com/gin-gonic/gin"
)
//处理api的静态内容
func ApiStatic(r *gin.RouterGroup) {
r.GET("/avatar/:filename", func(ctx *gin.Context) {
filename := ctx.Param("filename")
dst := path.Join(models.ConfigsFile.Pahts["avatar"], filename)
if models.FileExists(dst) {
ctx.File(dst)
} else {
//找不到文件
ctx.String(404, "file not found")
}
})
}
+114 -1
View File
@@ -1,8 +1,10 @@
package routers
import (
"errors"
"fmt"
"ops/models"
"path"
"strconv"
"time"
@@ -80,6 +82,33 @@ type From_user_changepass struct {
Newpass string `json:"newpass"`
}
func AuthenticationAuthorityFromCookie(c string) (*models.TabUser_, error) {
if c != "" {
cookie := models.TabCookie_{
Value: c,
}
if models.DB.Where(&cookie).First(&cookie).Error == nil {
//找到cookie,验证cookie有效性,以及更新cookie
if models.CheckCookiesAndUpdate(&cookie) {
//cookie有效
//载入user
user := models.TabUser_{
ID: cookie.UserID,
}
models.DB.Where(&user).First(&user)
return &user, nil
} else {
return nil, errors.New("cookie 过期")
}
} else {
return nil, errors.New("cookie Not Fund")
}
} else {
return nil, errors.New("cookie 参数错误")
}
}
func AuthenticationAuthority(ctx *gin.Context) (bool, models.TabUser_, map[string]interface{}) {
var user models.TabUser_
@@ -187,8 +216,92 @@ func ApiUser(r *gin.RouterGroup) {
//修改用户头像
r.POST("/updateAvatar", func(ctx *gin.Context) {
cookie := ctx.PostForm("cookie")
user, err := AuthenticationAuthorityFromCookie(cookie)
if err == nil {
file, err := ctx.FormFile("file")
if err == nil {
if file.Filename != "" {
//限制文件大小
if file.Size > 512 {
//头像裁剪过限制1M应该差不多
if file.Size < 1048576 {
//判断mime
mimeType, err := models.GetFileMime(file)
if err == nil {
file_extname := models.ConfigsFile.AllowImageMime[mimeType]
if file_extname != "" {
//haxi文件
file_hashi_name, err := models.SHA256HashFile(file)
if err == nil {
dst := path.Join(models.ConfigsFile.Pahts["avatar"], file_hashi_name+file_extname)
var is_save_ok = false
//判断文件是否存在避免重复保存
if models.FileExists(dst) {
//fmt.Println("文件存在")
is_save_ok = true
ReturnJson(ctx, "apiOK", nil)
} else {
//fmt.Println("文件no存在")
ferr := ctx.SaveUploadedFile(file, dst)
if ferr == nil {
//文件保存成功
//fmt.Print("save_ok")
is_save_ok = true
ReturnJson(ctx, "apiOK", nil)
} else {
fmt.Print(ferr)
ReturnJson(ctx, "postErr", nil)
}
}
if is_save_ok {
//修改数据库内容
var user_info_fund models.TabUserInfo_
user_info_fund.UserID = user.ID
var user_update_avatar models.TabUserInfo_
user_update_avatar.AvatarPath = file_hashi_name + file_extname
models.DB.Where(&user_info_fund).Updates(&user_update_avatar)
}
} else {
ReturnJson(ctx, "postErr", nil)
}
} else {
ReturnJson(ctx, "file_mime_err", nil)
}
} else {
ReturnJson(ctx, "postErr", nil)
}
} else {
ReturnJson(ctx, "file_size_err", nil)
}
} else {
ReturnJson(ctx, "file_size_err", nil)
}
} else {
ReturnJson(ctx, "file_name_err", nil)
}
} else {
ReturnJson(ctx, "file_get_err", nil)
}
} else {
ReturnJson(ctx, "userCookieError", nil)
}
ReturnJson(ctx, "jsonErr", nil)
})
//更新用户info
+10
View File
@@ -22,3 +22,13 @@ func ReturnJson(ctx *gin.Context, errMsg string, data map[string]interface{}) {
//ctx.Abort()
}
func Return_file(ctx *gin.Context, file_path string, preview bool) {
if preview {
ctx.File(file_path)
} else {
//需要从数据库拉取原始文件名
//ctx.FileAttachment(file_info.Path, file_info.Name)
}
}