12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package handlers
- import (
- "fmt"
- "github.com/gin-gonic/gin"
- "github.com/spf13/viper"
- "go.uber.org/zap"
- "passport/app/models"
- "passport/logger"
- "passport/pkg/ierr"
- "passport/pkg/util"
- "path/filepath"
- )
- func UploadFile(c *gin.Context) {
- var userId = c.GetString("uid")
- var f, err = c.FormFile("file")
- if err != nil {
- ResponseErr(c, ierr.NewIError(ierr.ReceiveRequestFileFail, err.Error()))
- return
- }
- var saveDir = viper.GetString("file.path")
- var host = viper.GetString("file.host")
- var name = fmt.Sprintf("%s_%d", util.RandomString(12), util.Now13()%1e9) + filepath.Ext(f.Filename)
- var path = filepath.Join(saveDir, name)
- var fileModel = &models.File{
- Url: host + name,
- Name: f.Filename,
- Path: path,
- Size: f.Size,
- Ext: filepath.Ext(f.Filename),
- UserId: "mock_user_id",
- }
- err = c.SaveUploadedFile(f, path)
- if err != nil {
- logger.Error("[UploadFile] save file to disk error",
- zap.Any("file", fileModel),
- zap.Error(err))
- ResponseErr(c, err)
- return
- }
- err = fileModel.Save()
- if err != nil {
- logger.Error("[UploadFile] save file info to db error",
- zap.Any("file", fileModel),
- zap.Error(err))
- ResponseErr(c, err)
- return
- }
- var resp = models.FileResponse{
- Url: fileModel.Url,
- Name: fileModel.Name,
- Size: fileModel.Size,
- Ext: fileModel.Ext,
- UserId: userId,
- }
- ResponseSuccess(c, resp)
- }
|