Sling Academy
Home/Golang/Using Multipart Requests for File Uploads in Go

Using Multipart Requests for File Uploads in Go

Last updated: November 27, 2024

Uploading files in web applications is a common task, and Go makes it remarkably straightforward, especially when dealing with multipart/form-data. In this article, we'll cover how to handle file uploads using multipart requests in Go.

Setting Up Your Go Project

Begin by creating a new directory for your Go project. You can name it fileupload or any name of your choice.

Inside this directory, initialize your Go module:

go mod init fileupload

Creating the HTML Form

To facilitate file uploads, you need an HTML form that allows users to select files. Create an index.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload File</title>
</head>
<body>
    <h1>Upload a File</h1>
    <form method="POST" action="/upload" enctype="multipart/form-data">
        <input type="file" name="uploadfile"/>
        <br/>
        <input type="submit" value="Upload"/>
    </form>
</body>
</html>

Handling File Uploads in Go

Create a main.go file where we will implement the logic for handling HTTP requests and file uploads:

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
)

func uploadFile(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
        return
    }

    file, handler, err := r.FormFile("uploadfile")
    if err != nil {
        fmt.Fprintf(w, "Error retrieving the file: %v", err)
        return
    }
    defer file.Close()

    f, err := os.OpenFile(handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Fprintf(w, "Error saving the file: %v", err)
        return
    }
    defer f.Close()

    io.Copy(f, file)
    fmt.Fprintf(w, "File uploaded successfully: %v", handler.Filename)
}

func main() {
    http.HandleFunc("/upload", uploadFile)
    fmt.Println("Starting server at :8080")
    http.ListenAndServe(":8080", nil)
}

This Go program sets up a server listening on port 8080 and expects file uploads at the /upload endpoint. The uploadFile function checks the request method, extracts the file from the request, and then writes it to the server's disk with the original filename.

Running Your File Upload Service

Now, it's time to test your file upload functionality:

go run main.go

Visit http://localhost:8080 in your browser, choose a file for upload, and then submit the form. If everything is set up correctly, you'll see a message indicating a successful file upload, and you'll find the uploaded file in your project directory.

Conclusion

With Go's net/http package, handling file uploads with multipart requests is a clean and straightforward process. This simple application efficiently receives a file from a client and stores it on the server, easily expandable into more complex applications with additional file handling logic.

Next Article: Streaming Large Files with Go HTTP

Previous Article: Setting Up Reverse Proxies with Go

Series: Networking and Server

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant