From bde92de924c7509339b4d6c05a7487d0256db41d Mon Sep 17 00:00:00 2001 From: Fenny Date: Wed, 8 Jan 2020 02:04:04 -0500 Subject: [PATCH] Add Form() to README --- context.go | 12 ++++++------ docs/README.md | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 6 deletions(-) diff --git a/context.go b/context.go index 61abd987..2f7da187 100644 --- a/context.go +++ b/context.go @@ -71,7 +71,7 @@ func (ctx *Ctx) BasicAuth() (user, pass string, ok bool) { } // Form : -func (ctx *Ctx) MultipartForm() *multipart.Form { +func (ctx *Ctx) Form() *multipart.Form { form, err := ctx.Fasthttp.MultipartForm() if err != nil { return nil @@ -79,6 +79,11 @@ func (ctx *Ctx) MultipartForm() *multipart.Form { return form } +// SaveFile : +func (ctx *Ctx) SaveFile(fh *multipart.FileHeader, path string) { + fasthttp.SaveMultipartFile(fh, path) +} + // // FormValue : // func (ctx *Ctx) FormValues(key string) (values []string) { // form, err := ctx.Fasthttp.MultipartForm() @@ -98,11 +103,6 @@ func (ctx *Ctx) MultipartForm() *multipart.Form { // return files // } -// SaveFile : -func (ctx *Ctx) SaveFile(fh *multipart.FileHeader, path string) { - fasthttp.SaveMultipartFile(fh, path) -} - // Body : func (ctx *Ctx) Body(args ...interface{}) string { if len(args) == 0 { diff --git a/docs/README.md b/docs/README.md index 446536ca..92e19b95 100644 --- a/docs/README.md +++ b/docs/README.md @@ -550,6 +550,41 @@ app.Get("/", func(c *fiber.Ctx) { }) ``` +#### Form +To access multipart form entries, you can parse the binary with .Form(). +This returns a map[string][]string, so given a key the value will be a string slice. +So accepting multiple files or values is easy, as shown below! +```go +// Function signature +c.Form() + +// Example +app.Post("/", func(c *fiber.Ctx) { + // Parse the multipart form + if form := c.Form(); form != nil { + // => *multipart.Form + + if token := form.Value["token"]; len(token) > 0 { + // Get key value + fmt.Println(token[0]) + } + + // Get all files from "documents" key + files := form.File["documents"] + // => []*multipart.FileHeader + + // Loop trough files + for _, file := range files { + fmt.Println(file.Filename, file.Size, file.Header["Content-Type"][0]) + // => "tutorial.pdf" 360641 "application/pdf" + + // Save the files to disk + c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)) + } + } +}) +``` + #### Get Returns the HTTP response header specified by field. The match is case-insensitive. ```go @@ -768,6 +803,15 @@ app.Get("/", func(c *fiber.Ctx) { }) ``` +#### SaveFile +This function is used to save any multipart file to disk. +You can see a working example here: [Multiple file upload](#form) + +```go +// Function signature +c.SaveFile(fh *multipart.FileHeader, path string) +``` + #### Send Sends the HTTP response.