How to implement multiple file uploads with Go

In this article, we will see how to implement multiple file uploads in a web application developed with the Go programming language. This approach is useful for handling the upload of multiple files simultaneously, such as images or documents, by users.

Implementation

We will create a Go application that allows users to upload multiple files.

1. Configure the HTTP Server

We create a file main.go and set up an HTTP server to handle upload requests.

package main

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

func main() {
	http.HandleFunc("/upload", uploadHandler)
	http.HandleFunc("/", formHandler)

	fmt.Println("Server listening on port 8080...")
	http.ListenAndServe(":8080", nil)
}

2. Create the HTML Form

The HTML form allows users to select multiple files and send them to the server.

func formHandler(w http.ResponseWriter, r *http.Request) {
	html := `
	<!DOCTYPE html>
	<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Multiple File Upload</title>
	</head>
	<body>
		<h1>Upload Your Files</h1>
		<form action="/upload" method="post" enctype="multipart/form-data">
			<input type="file" name="files" multiple>
			<br><br>
			<button type="submit">Upload</button>
		</form>
	</body>
	</html>
	`
	w.Write([]byte(html))
}

3. Handle File Upload

We create a handler that processes the files sent by the HTML form.

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	r.ParseMultipartForm(10 << 20) // Limit of 10 MB

	files := r.MultipartForm.File["files"]
	for _, fileHeader := range files {
		file, err := fileHeader.Open()
		if err != nil {
			http.Error(w, "Error opening file", http.StatusInternalServerError)
			return
		}
		defer file.Close()

		out, err := os.Create("uploads/" + fileHeader.Filename)
		if err != nil {
			http.Error(w, "Error creating file", http.StatusInternalServerError)
			return
		}
		defer out.Close()

		_, err = io.Copy(out, file)
		if err != nil {
			http.Error(w, "Error writing file", http.StatusInternalServerError)
			return
		}
	}

	w.Write([]byte("Upload completed!"))
}

Testing the Application

Start the application by running the command:

go run main.go

Access the upload form at http://localhost:8080 and test the upload of multiple files.

Conclusion

We have seen how to implement multiple file uploads with Go using an HTML form and an HTTP server. This approach can be customized to meet the specific needs of your application.

Back to top