gin-blog/internal/routess/api/upload.go

72 lines
1.8 KiB
Go
Raw Permalink Normal View History

2021-05-28 10:40:39 +00:00
package api
import (
"blog/global"
"blog/internal/service"
"blog/pkg/app"
"blog/pkg/convert"
"blog/pkg/errorcode"
"blog/pkg/upload"
"github.com/gin-gonic/gin"
2021-05-31 03:17:33 +00:00
"os"
"path"
"strings"
2021-05-28 10:40:39 +00:00
)
type Upload struct{}
func NewUpload() Upload {
return Upload{}
}
2021-05-31 03:17:33 +00:00
func ReadFile(c *gin.Context) {
fileName := strings.TrimLeft(c.Request.RequestURI, "/")
_, fileName = path.Split(fileName)
fileName = path.Join(global.AppSetting.UploadSavePath, fileName)
_, err := os.Stat(fileName)
if os.IsNotExist(err) {
if err != nil {
app.NewResponse(c).ToErrorResponse(errorcode.NotFound.WithDetails(err.Error()))
return
}
}
c.File(fileName)
}
// UploadFile
2021-05-28 10:40:39 +00:00
// @Summary 上传图片
// @Produce json
// @Security ApiKeyAuth
2021-05-28 10:40:39 +00:00
// @Param type formData int true "文件类型1图片" required Enums(1,2,3)
2021-05-31 02:13:26 +00:00
// @Param file formData file true "文件"
2021-05-28 10:40:39 +00:00
// @Success 200 {object} service.FileInfo "成功"
// @Failure 400 {object} errorcode.Error "请求错误"
// @Failure 500 {object} errorcode.Error "内部错误"
// @Router /upload/file [post]
func (u Upload) UploadFile(c *gin.Context) {
response := app.NewResponse(c)
file, fileHeader, err := c.Request.FormFile("file")
if err != nil {
response.ToErrorResponse(errorcode.InvalidParams.WithDetails(err.Error()))
return
}
fileType := convert.StrTo(c.PostForm("type")).MustInt()
if fileHeader == nil || fileType <= 0 {
response.ToErrorResponse(errorcode.InvalidParams)
return
}
svc := service.New(c.Request.Context())
fileInfo, err := svc.UploadFile(upload.FileType(fileType), file, fileHeader)
if err != nil {
global.Logger.Errorf("svc.UploadFile err: %v", err)
response.ToErrorResponse(errorcode.ErrorUploadFileFail.WithDetails(err.Error()))
return
}
response.ToResponse(gin.H{
"file_access_url": fileInfo.AccessUrl,
})
}