From 882149eee5e1fad89fe2b6194a2707488f4d8b85 Mon Sep 17 00:00:00 2001 From: xing Date: Mon, 31 May 2021 11:17:33 +0800 Subject: [PATCH] filesystem --- .gitignore | 1 + internal/routess/api/upload.go | 17 +++++++++++++++++ internal/routess/router.go | 4 ++++ 3 files changed, 22 insertions(+) diff --git a/.gitignore b/.gitignore index f7b9fb0..5aca732 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ .idea storage/* blog.iml +go.sum # Dependency directories (remove the comment below to include it) # vendor/ diff --git a/internal/routess/api/upload.go b/internal/routess/api/upload.go index 6bf56fa..533fe07 100644 --- a/internal/routess/api/upload.go +++ b/internal/routess/api/upload.go @@ -8,6 +8,9 @@ import ( "blog/pkg/errorcode" "blog/pkg/upload" "github.com/gin-gonic/gin" + "os" + "path" + "strings" ) type Upload struct{} @@ -16,6 +19,20 @@ 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) +} + // @Summary 上传图片 // @Produce json // @Param type formData int true "文件类型1图片" required Enums(1,2,3) diff --git a/internal/routess/router.go b/internal/routess/router.go index e1d945c..f07e9ca 100644 --- a/internal/routess/router.go +++ b/internal/routess/router.go @@ -2,12 +2,14 @@ package routess import ( _ "blog/docs" + "blog/global" "blog/internal/middleware" "blog/internal/routess/api" v1 "blog/internal/routess/api/v1" "github.com/gin-gonic/gin" swaggerFiles "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" + "net/http" ) func NewRouter() *gin.Engine { @@ -19,6 +21,8 @@ func NewRouter() *gin.Engine { tag := v1.NewTag() upload := api.NewUpload() r.POST("/upload/file", upload.UploadFile) + r.StaticFS("/static", http.Dir(global.AppSetting.UploadSavePath)) + //r.GET("/static/*any",api.ReadFile) r.GET("/doc/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) apiv1 := r.Group("/api/v1") {