go iris框架文件上传下载

在 Iris 框架中,可以使用内置的 iris 包中的 Context 对象来处理文件上传和下载。以下是一个简单的示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
 
import (
    "github.com/kataras/iris/v12"
)
 
func main() {
    app := iris.New()
 
    // 处理文件上传
    app.Post("/upload", func(ctx iris.Context) {
        file, info, err := ctx.FormFile("file")
        if err != nil {
            ctx.StatusCode(iris.StatusBadRequest)
            ctx.WriteString(err.Error())
            return
        }
        defer file.Close()
 
        // 保存文件到本地
        err = ctx.SaveFormFile(file, "./uploads/" + info.Filename)
        if err != nil {
            ctx.StatusCode(iris.StatusInternalServerError)
            ctx.WriteString(err.Error())
            return
        }
 
        ctx.WriteString("文件上传成功")
    })
 
    // 处理文件下载
    app.Get("/download", func(ctx iris.Context) {
        filename := ctx.URLParam("filename")
 
        // 打开文件
        file, err := os.Open("./uploads/" + filename)
        if err != nil {
            ctx.StatusCode(iris.StatusNotFound)
            ctx.WriteString("文件不存在")
            return
        }
        defer file.Close()
 
        // 设置响应头信息
        ctx.Header("Content-Disposition", "attachment; filename=" + filename)
        ctx.Header("Content-Type", "application/octet-stream")
        ctx.Header("Content-Length", strconv.FormatInt(info.Size(), 10))
 
        // 将文件写入响应
        _, err = io.Copy(ctx.ResponseWriter(), file)
        if err != nil {
            ctx.StatusCode(iris.StatusInternalServerError)
            ctx.WriteString(err.Error())
            return
        }
    })
 
    app.Run(iris.Addr(":8080"))
}

  上述代码中,/upload 路由处理文件上传,将文件保存到本地的 ./uploads 目录下。/download 路由处理文件下载,先打开本地文件,然后设置响应头信息,最后将文件内容写入响应体中。

posted @   根号三先生  阅读(394)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示