Skip to content

🐛 [Bug]: BodyParser does not parse multipart.FileHeader fields in multipart/form-data requests #3286

@SadikSunbul

Description

@SadikSunbul

Bug Description

When using the BodyParser method in Fiber, it fails to automatically parse file fields (multipart.FileHeader) in multipart/form-data requests. While other fields like name and pass are successfully parsed, file fields remain nil, even if they are present in the request payload. This makes it necessary to manually retrieve files using the c.FormFile method, which defeats the purpose of automatic parsing via BodyParser.

How to Reproduce

1-> Create a POST request using curl or Postman with the following payload:
Field name: john
Field pass: doe
File file: Upload any test file.
2-> Observe that the name and pass fields are parsed correctly, but the file field is not parsed (p.File is nil).

cURL

curl -X POST http://localhost:3000/ \
  -F "name=john" \
  -F "pass=doe" \
  -F "file=@testfile.txt"

Outputs

file:<nil>
2025/01/18 12:00:00 john
2025/01/18 12:00:00 doe
Name:john - Pass:doe - File:<nil>

Expected Behavior

The BodyParser method should correctly parse all fields in a multipart/form-data request, including files, into the corresponding struct fields (*multipart.FileHeader).

Fiber Version

v2.52.6

Code Snippet (optional)

package main

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"log"
	"mime/multipart"
)

type Person struct {
	Name string                `json:"name" xml:"name" form:"name"`
	Pass string                `json:"pass" xml:"pass" form:"pass"`
	File *multipart.FileHeader `json:"file" xml:"file" form:"file"`
}

func main() {
	app := fiber.New()

	app.Post("/", func(c *fiber.Ctx) error {
		p := new(Person)

		if err := c.BodyParser(p); err != nil {
			return err
		}

		//file, _ := c.FormFile("file"). // This place works

		fmt.Printf("file:%v \n", p.File)

		log.Println(p.Name) // "john"
		log.Println(p.Pass) // "doe"

		c.SendString(fmt.Sprintf("Name:%v - Pass:%v - File: %v", p.Name, p.Pass, p.File.Filename))
		return c.SendStatus(fiber.StatusOK)
	})

	app.Listen(":3000")
}

Checklist:

  • I agree to follow Fiber's Code of Conduct.
  • I have checked for existing issues that describe my problem prior to opening this one.
  • I understand that improperly formatted bug reports may be closed without explanation.

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions