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" "os" "path" "strings" ) type Upload struct{} func NewUpload() Upload { return Upload{} } 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 // @Summary 上传图片 // @Produce json // @Security ApiKeyAuth // @Param type formData int true "文件类型1图片" required Enums(1,2,3) // @Param file formData file true "文件" // @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, }) }