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"
- )
- /**
- * showdoc
- * @catalog 文件上传
- * @title 文件上传通用接口
- * @description 文件上传通用接口
- * @method POST
- * @url ~/v1/file/upload
- * @return {"code":0,"data":{"url":"/xRTZHWUsaD6H_715747502.mp4","name":"认真且怂.mp4","size":3409702,"ext":".mp4","user_id":"26640398931722340"}}
- * @return_param url string url地址
- * @return_param name string 文件名
- * @return_param size int 文件大小
- * @return_param ext string 文件扩展名
- * @return_param user_id string 用户id
- * @remark 无
- * @number 1
- */
- 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)
- }
|