Skip to content

Commit

Permalink
feat: download-image 接口
Browse files Browse the repository at this point in the history
  • Loading branch information
RockChinQ committed Apr 12, 2024
1 parent ab75928 commit a208b07
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
31 changes: 31 additions & 0 deletions backend/controller/postapi.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package controller

import (
"bytes"

"github.com/RockChinQ/Campux/backend/service"
"github.com/gin-gonic/gin"
)
Expand All @@ -20,6 +22,8 @@ func NewPostRouter(rg *gin.RouterGroup, ps service.PostService) *PostRouter {
// bind routes
group.POST("/upload-image", pr.UploadImage)
group.POST("/post-new", pr.PostNew)
// download-image/{image-key}
group.GET("/download-image/:key", pr.DownloadImage)

return pr
}
Expand Down Expand Up @@ -85,3 +89,30 @@ func (pr *PostRouter) PostNew(c *gin.Context) {
"id": id,
})
}

// 下载图片
func (pr *PostRouter) DownloadImage(c *gin.Context) {
_, err := pr.GetUin(c)

if err != nil {
pr.StatusCode(c, 401, err.Error())
return
}

key := c.Param("key")

buf := bytes.NewBuffer(nil)

err = pr.PostService.DownloadImage(key, buf)

if err != nil {
pr.Fail(c, 1, err.Error())
return
}

// 下载图片,直接返回内容
// data, err := pr.PostService.DownloadImage(key)
c.Writer.Header().Set("Content-Type", "image/jpeg")

c.Data(200, "application/octet-stream", buf.Bytes())
}
13 changes: 13 additions & 0 deletions backend/oss/minio.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,16 @@ func (m *MinioClient) UploadFromIO(ioReader io.Reader, suffix string) (string, e
_, err := m.Client.PutObject(context.Background(), m.Bucket, objectName, ioReader, -1, minio.PutObjectOptions{})
return objectName, err
}

// 下载文件到io.Writer
func (m *MinioClient) DownloadToIO(objectName string, ioWriter io.Writer) error {
obj, err := m.Client.GetObject(context.Background(), m.Bucket, objectName, minio.GetObjectOptions{})

if err != nil {
return err
}

_, err = io.Copy(ioWriter, obj)

return err
}
4 changes: 4 additions & 0 deletions backend/service/post.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ func (ps *PostService) UploadImage(ioReader io.Reader, suffix string) (string, e
return ps.OSS.UploadFromIO(ioReader, suffix)
}

func (ps *PostService) DownloadImage(key string, ioWriter io.Writer) error {
return ps.OSS.DownloadToIO(key, ioWriter)
}

func (ps *PostService) PostNew(uuid string, uin int64, text string, images []string, anon bool) (int, error) {

id, err := ps.DB.CountPost()
Expand Down

0 comments on commit a208b07

Please sign in to comment.