
hertz文件相关
文件上传
go
package main
import (
"context"
"io/ioutil"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cloudwego/hertz/pkg/protocol/consts"
)
func main() {
h := server.Default()
// 处理文件上传
h.POST("/upload", func(c context.Context, ctx *app.RequestContext) {
// 获取上传的文件
fileHeader, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(consts.StatusBadRequest, map[string]interface{}{
"error": "File is required",
})
return
}
// 打开上传的文件
file, err := fileHeader.Open()
if err != nil {
ctx.JSON(consts.StatusInternalServerError, map[string]interface{}{
"error": "Failed to open file",
})
return
}
defer file.Close()
// 读取文件内容
fileContent, err := ioutil.ReadAll(file)
if err != nil {
ctx.JSON(consts.StatusInternalServerError, map[string]interface{}{
"error": "Failed to read file",
})
return
}
ctx.JSON(consts.StatusOK, map[string]interface{}{
"filename": fileHeader.Filename,
"size": fileHeader.Size,
"content_len": len(fileContent),
"message": "File uploaded successfully",
})
})
h.Spin()
}