How do I handle file uploads with Fiber in Go?

Handling file uploads in Go using the Fiber web framework can be accomplished easily with its built-in middleware. Below, you'll find a simple example that showcases how to set up a file upload endpoint, allowing users to upload files to your server.


package main

import (
    "github.com/gofiber/fiber/v2"
    "log"
    "os"
)

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

    app.Post("/upload", func(c *fiber.Ctx) error {
        // Form the uploaded file
        file, err := c.FormFile("file")
        if err != nil {
            return c.Status(fiber.StatusBadRequest).SendString("No file uploaded")
        }

        // Save the file to the /uploads directory
        err = c.SaveFile(file, "./uploads/"+file.Filename)
        if err != nil {
            return c.Status(fiber.StatusInternalServerError).SendString("Could not save file")
        }

        return c.SendString("File uploaded successfully")
    })

    // Start the Fiber application
    log.Fatal(app.Listen(":3000"))
}
    

Go Fiber file uploads web framework Golang handling files server uploads middleware example code