Kratos: http上传、下载和预览图片

在Web开发中,经常需要对图片上传、下载或预览。Kratos一套轻量级Go微服务框架,本文将介绍在Kratos中要如何实现。

接着我们将以Kratos初始化的项目(kratos new helloworld -r https://gitee.com/go-kratos/kratos-layout.git)为基点,进行修改,详细如下:

  1. 通过http请求form-data的方式,上传图片并保存
  2. 通过http请求下载、预览图片

1. 修改Service:上传、下载和预览

1.1 上传:

go 复制代码
package service

import (
    "context"
    transporthttp "github.com/go-kratos/kratos/v2/transport/http"
    v1 "helloworld/api/helloworld/v1"
    "helloworld/internal/biz"
    "io"
    "os"
) 
// 上传
func (s *GreeterService) Upload(ctx transporthttp.Context) (err error) {
    file, header, err := ctx.Request().FormFile("file")
    if err != nil {
       return
    }
    defer file.Close()

    // 修改文件名并创建保存图片
    imageFile, err := os.Create("./band_" + header.Filename) 
    if err != nil {
       return
    }
    defer imageFile.Close()

    // 将文件内容复制到保存的文件中
    _, err = io.Copy(imageFile, file)
    if err != nil {
       return
    }
    return nil
}

上例中,我们通过ctx.Request().FormFile 获取文件,通过os.Create将文件的名称修改为band_ + w文件名,最后io.Copy将文件内容复制到保存的文件中。

1.2 下载:

go 复制代码
func (s *GreeterService) Download(ctx transporthttp.Context) error {
    imageFile, err := os.Open("./go.png")
    if err != nil {
       return err
    }
    defer imageFile.Close()
    payload, err := io.ReadAll(imageFile)
    if err != nil {
       return err
    } 
    // 设置HTTP响应头
    // 打开为预览
    //ctx.Response().Header().Set("Content-Type", "image/png")
    // 打开为下载
    ctx.Response().Header().Set("Content-Type", "application/octet-stream")
    ctx.Response().Header().Set("Content-Disposition", "attachment; filename=go2.png") 
    // 将结果写入
    _, err = ctx.Response().Write(payload)
    return err
}

上例中,我们通过设置了Header的不同Content-Type来分别实现是预览或者下载。 其中

  • application/octet-stream,通知浏览器以二进制流的形式下载文件。

  • Content-Disposition,其中attachment表示将文件作为附件下载,filename=download.png指定了下载文件的名称。

2. 注册路由

go 复制代码
package server

import (
    v1 "helloworld/api/helloworld/v1"
    "helloworld/internal/conf"
    "helloworld/internal/service"

    "github.com/go-kratos/kratos/v2/log"
    "github.com/go-kratos/kratos/v2/middleware/recovery"
    "github.com/go-kratos/kratos/v2/transport/http"
)

// NewHTTPServer new a HTTP server.
func NewHTTPServer(c *conf.Server, greeter *service.GreeterService, logger log.Logger) *http.Server {
    var opts = []http.ServerOption{
       http.Middleware(
          recovery.Recovery(),
       ),
    }
    if c.Http.Network != "" {
       opts = append(opts, http.Network(c.Http.Network))
    }
    if c.Http.Addr != "" {
       opts = append(opts, http.Address(c.Http.Addr))
    }
    if c.Http.Timeout != nil {
       opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
    }
    srv := http.NewServer(opts...)
    v1.RegisterGreeterHTTPServer(srv, greeter)

    //路由注册
    route := srv.Route("/")
    //图片上传
    route.POST("/upload", greeter.Upload)
    //图片下载
    route.GET("/download", greeter.Download)

    return srv
} 

测试1. 上传

  1. 启动Kratos HelloWorld Http 服务
js 复制代码
> msg=[HTTP] server listening on: [::]:8001
  1. 我们通过http服务localhost:8001, 路由/upload,上传本地图片heibao.jpg,curl如下
cmd 复制代码
curl --location 'http://localhost:8001/upload?file=null' \
--form 'file=@"/D:/heibao.jpg"'

在工作目录下,多出了一个band_heibao.jpg的文件,说明上传并图片成功。尝试打开图片

正常显示。

测试2: 下载、预览

在GeeteeingService.Download的代码,通过修改http.Header设置来实现预览

go 复制代码
ctx.Response().Header().Set("Content-Type", "image/png") 

打开浏览器,输入http://localhost:8001/download,显示如下:

如果修改为

go 复制代码
//ctx.Response().Header().Set("Content-Type", "image/png")
ctx.Response().Header().Set("Content-Type", "application/octet-stream")
ctx.Response().Header().Set("Content-Disposition", "attachment; filename=go2.png")

则为浏览器下载

参考

相关推荐
郑洁文19 小时前
基于Python的HTTP服务漏洞信息收集工具设计与实现
开发语言·python·http
Andy Dennis21 小时前
nsq学习记录
消息队列·go·nsq
草莓熊Lotso1 天前
【Linux网络】深入理解 HTTP 协议(一):从基础概念到 URL 编码解码
linux·网络·c++·网络协议·http·软件工程
SilentSamsara1 天前
HTTP 客户端实战:httpx/重试/限速/连接池/中间件设计
开发语言·网络·python·http·青少年编程·中间件·httpx
韦胖漫谈IT1 天前
选语言不是站队,是选适合问题的工具
java·python·ai·rust·go·技术落地
草莓熊Lotso1 天前
【Linux网络】深入理解 HTTP 协议(二):从协议格式到手写工业级 HTTP 服务器
linux·运维·服务器·网络·c++·http
喵个咪1 天前
GoWind Toolkit Go后端代码生成 完整全流程实战
后端·go·orm
夜悊2 天前
Go网络编程的学习代码示例:客户端/服务端(C/S)模型
go
审判长烧鸡2 天前
【AI问答】GO代码循环返值
go
捧 花2 天前
Eino框架记忆功能实现指南
go·agent·eino