87 lines
2.1 KiB
Go
87 lines
2.1 KiB
Go
package admin
|
||
|
||
import (
|
||
"blog/internal/model/admin"
|
||
"blog/internal/service"
|
||
"blog/third_party/SessionUtil"
|
||
"blog/third_party/database"
|
||
"time"
|
||
|
||
"github.com/google/uuid"
|
||
"github.com/kataras/iris/v12"
|
||
"github.com/kataras/iris/v12/sessions"
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
type FileController struct {
|
||
Ctx iris.Context
|
||
Session *sessions.Session
|
||
}
|
||
|
||
type uploadResponse struct {
|
||
Success int `json:"success"`
|
||
Message string `json:"message"`
|
||
Url string `json:"url"`
|
||
Location string `json:"location"`
|
||
}
|
||
|
||
func (ctrl *FileController) Get() {
|
||
ctrl.Ctx.View("/admin/file/index.html")
|
||
}
|
||
|
||
func (ctrl *FileController) GetList() {
|
||
page := ctrl.Ctx.URLParamIntDefault("page", 0)
|
||
itemsPerPage := ctrl.Ctx.URLParamIntDefault("itemsPerPage", 10)
|
||
pages := service.FileService.PageSysFiles(page, itemsPerPage)
|
||
|
||
ctrl.Ctx.JSON(pages)
|
||
}
|
||
|
||
func (ctrl *FileController) PostUpload() {
|
||
file, fileHeader, err := ctrl.Ctx.FormFile("editormd-image-file")
|
||
if err != nil {
|
||
file, fileHeader, err = ctrl.Ctx.FormFile("file")
|
||
if err != nil {
|
||
return
|
||
}
|
||
}
|
||
user := SessionUtil.GetUser(ctrl.Session)
|
||
fileId := uuid.NewString()
|
||
fileName := fileHeader.Filename
|
||
fileSize := fileHeader.Size
|
||
var bytes []byte = make([]byte, fileSize)
|
||
file.Read(bytes)
|
||
|
||
sysFile := admin.SysFile{
|
||
Id: fileId,
|
||
FileName: fileName,
|
||
FileSize: fileSize,
|
||
CreateBy: user.Username,
|
||
CreateTime: time.Now().UnixMilli(),
|
||
Data: bytes, State: "1",
|
||
Del: 0,
|
||
}
|
||
err = database.GormTemplate.Transaction(func(tx *gorm.DB) error {
|
||
err2 := tx.Table("common_files").Create(sysFile).Error
|
||
return err2
|
||
// log.Println(sysFile)
|
||
// return nil
|
||
})
|
||
if err != nil {
|
||
// {
|
||
// success : 0 | 1, // 0 表示上传失败,1 表示上传成功
|
||
// message : "提示的信息,上传成功或上传失败及错误信息等。",
|
||
// url : "图片地址" // 上传成功时才返回
|
||
// }
|
||
ctrl.Ctx.JSON(uploadResponse{Success: 0, Message: "上传失败"})
|
||
return
|
||
}
|
||
|
||
ctrl.Ctx.JSON(uploadResponse{
|
||
Success: 1,
|
||
Message: "上传成功",
|
||
Url: "/file/" + fileId,
|
||
Location: "/file/" + fileId,
|
||
})
|
||
}
|