go iris框架文件上传下载
在 Iris 框架中,可以使用内置的
iris
包中的 Context
对象来处理文件上传和下载。以下是一个简单的示例代码:
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
路由处理文件下载,先打开本地文件,然后设置响应头信息,最后将文件内容写入响应体中。
本文来自博客园,作者:根号三先生,转载请注明原文链接:https://www.cnblogs.com/sin3degree/p/17147345.html