mirror of
https://gitee.com/johng/gf
synced 2026-07-07 06:15:15 +08:00
44
example/httpserver/upload_file/main.go
Normal file
44
example/httpserver/upload_file/main.go
Normal file
@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/gogf/gf/v2/frame/g"
|
||||
"github.com/gogf/gf/v2/net/ghttp"
|
||||
)
|
||||
|
||||
type UploadReq struct {
|
||||
g.Meta `path:"/upload" method:"POST" tags:"Upload" mime:"multipart/form-data" summary:"上传文件"`
|
||||
File *ghttp.UploadFile `p:"file" type:"file" dc:"选择上传文件"`
|
||||
Msg string `dc:"消息"`
|
||||
}
|
||||
type UploadRes struct {
|
||||
FileName string `json:"fileName"`
|
||||
}
|
||||
|
||||
type cUpload struct{}
|
||||
|
||||
func (u cUpload) Upload(ctx context.Context, req *UploadReq) (*UploadRes, error) {
|
||||
if req.File != nil {
|
||||
return &UploadRes{
|
||||
FileName: req.File.Filename,
|
||||
}, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
s := g.Server()
|
||||
s.Group("/", func(group *ghttp.RouterGroup) {
|
||||
group.Middleware(ghttp.MiddlewareHandlerResponse)
|
||||
group.Bind(cUpload{})
|
||||
})
|
||||
s.SetClientMaxBodySize(600 * 1024 * 1024) // 600M
|
||||
s.SetPort(8199)
|
||||
s.SetAccessLogEnabled(true)
|
||||
s.Run()
|
||||
}
|
||||
|
||||
// curl --location 'http://127.0.0.1:8199/upload' \
|
||||
// --form 'file=@"/D:/下载/goframe-v2.5.pdf"' \
|
||||
// --form 'msg="666"'
|
||||
@ -269,8 +269,6 @@ func (r *Request) parseForm() {
|
||||
return
|
||||
}
|
||||
if contentType := r.Header.Get("Content-Type"); contentType != "" {
|
||||
r.MakeBodyRepeatableRead(true)
|
||||
|
||||
var err error
|
||||
if gstr.Contains(contentType, "multipart/") {
|
||||
// multipart/form-data, multipart/mixed
|
||||
|
||||
@ -8,6 +8,7 @@ package ghttp_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@ -154,8 +155,11 @@ func Test_ClientMaxBodySize_File(t *testing.T) {
|
||||
t.Assert(gfile.PutBytes(path, data), nil)
|
||||
defer gfile.Remove(path)
|
||||
t.Assert(
|
||||
gstr.Trim(c.PostContent(ctx, "/", "name=john&file=@file:"+path)),
|
||||
"Read from request Body failed: http: request body too large",
|
||||
true,
|
||||
strings.Contains(
|
||||
gstr.Trim(c.PostContent(ctx, "/", "name=john&file=@file:"+path)),
|
||||
"http: request body too large",
|
||||
),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user