File Upload Example
This example demonstrates how to handle file uploads using Go Fiber.
Description
This project provides a basic setup for handling file uploads in a Go Fiber application. It includes examples for uploading single and multiple files, as well as saving files to different directories.
Requirements
Project Structure
single/main.go: Example for uploading a single file to the root directory.single_relative_path/main.go: Example for uploading a single file to a relative path.multiple/main.go: Example for uploading multiple files.go.mod: The Go module file.
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.gitcd recipes/upload-file -
Install the dependencies:
go mod download
Running the Examples
Single File Upload
-
Navigate to the
singledirectory:cd single -
Run the application:
go run main.go -
Use a tool like
curlor Postman to upload a file:curl -F "document=@/path/to/your/file" http://localhost:3000/
Single File Upload with Relative Path
-
Navigate to the
single_relative_pathdirectory:cd single_relative_path -
Run the application:
go run main.go -
Use a tool like
curlor Postman to upload a file:curl -F "document=@/path/to/your/file" http://localhost:3000/
Multiple File Upload
-
Navigate to the
multipledirectory:cd multiple -
Run the application:
go run main.go -
Use a tool like
curlor Postman to upload multiple files:curl -F "documents=@/path/to/your/file1" -F "documents=@/path/to/your/file2" http://localhost:3000/
Security
- Filename sanitization: All handlers use
filepath.Base(file.Filename)to strip any directory components from uploaded filenames, preventing path traversal attacks (e.g.,../../etc/passwd). - Body size limit: The app is configured with a 10 MB body limit (
BodyLimit: 10 * 1024 * 1024) to prevent denial-of-service via large uploads.
Code Overview
single/main.go
Handles uploading a single file to the root directory.
single_relative_path/main.go
Handles uploading a single file to a relative path (./uploads/) or a temp uploads directory (./uploads_relative/).
multiple/main.go
Handles uploading multiple files.
Conclusion
This example provides a basic setup for handling file uploads in a Go Fiber application. It can be extended and customized further to fit the needs of more complex applications.