Guide to creating a multiple image upload form using Golang

A step-by-step guide on how to create a form to upload multiple images simultaneously in Golang using the `net/http` library.

In this article, we will learn how to create an HTML form to upload multiple images and then process these files using Golang. We will use the net/http library to handle receiving the form data and storing the images in a destination folder.

Golang code:

package main

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

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	// Limit the size of the memory used for processing the upload
	r.ParseMultipartForm(10 << 20)

	// Retrieve the uploaded files from the form
	files := r.MultipartForm.File["files"]

	for _, fileHeader := range files {
		// Open the uploaded file
		file, err := fileHeader.Open()
		if err != nil {
			http.Error(w, "Unable to open file", http.StatusInternalServerError)
			return
		}
		defer file.Close()

		// Create a new file to store the uploaded content
		dst, err := os.Create(filepath.Join("uploads", fileHeader.Filename))
		if err != nil {
			http.Error(w, "Unable to save file", http.StatusInternalServerError)
			return
		}
		defer dst.Close()

		// Copy the uploaded file content to the new file
		if _, err := io.Copy(dst, file); err != nil {
			http.Error(w, "Unable to copy file", http.StatusInternalServerError)
			return
		}
	}

	fmt.Fprintln(w, "Upload successful!")
}

func main() {
	// Create the storage directory if it doesn't exist
	os.MkdirAll("uploads", os.ModePerm)

	// Define the handler for the /upload path
	http.HandleFunc("/upload", uploadHandler)

	// Create the HTML page for the upload form
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, `<html><body>
			<form action="/upload" method="post" enctype="multipart/form-data">
				Select multiple images: <input type="file" name="files" multiple>
				<input type="submit" value="Upload">
			</form>
			</body></html>`)
	})

	fmt.Println("Server running at http://localhost:8080")
	http.ListenAndServe(":8080", nil)
}

Detailed explanation:

  1. r.ParseMultipartForm(10 << 20): Limits the memory used for processing the file upload to 10MB.
  2. files := r.MultipartForm.File["files"]: Retrieves the list of uploaded files from the form.
  3. os.Create(filepath.Join("uploads", fileHeader.Filename)): Creates a new file in the "uploads" directory to store the uploaded file.
  4. io.Copy(dst, file): Copies the uploaded file content to the new file on the server.
  5. http.HandleFunc("/upload", uploadHandler): Defines the path that handles image upload requests.
  6. http.ListenAndServe(":8080", nil): Starts the server on port 8080.

System Requirements:

  • Go version 1.16 or higher

How to install Golang:

Download and install Golang from the official Go website.

Tips:

  • Ensure that the "uploads" directory has write permissions to store uploaded files.
  • Validate the file size and type before saving to avoid security vulnerabilities.
Tags: Golang, Upload


Related

JSON Web Token Authentication with Golang

A guide on how to implement JSON Web Token (JWT) authentication in a Golang application. This article details how to create, sign, and verify JWTs to secure an API.
Send JavaScript code to a website using Golang and Selenium

A guide on how to use Selenium in Golang to send JavaScript code to a website on the Chrome browser. The article provides specific code and detailed explanations.
How to Automatically Log in to a Website Using Selenium with Chrome in Golang

A guide on how to use Selenium in Golang to automatically log in to a website using the Chrome browser. This article provides specific code examples and detailed explanations of each step.
How to pass Authentication Header Token when POSTing data to an API using Golang

This guide explains how to pass an Authentication Header Token when making a POST request to an API using Golang. It covers handling HTTP requests, adding a token to the Header for authentication, and sending data to an API.
How to Get JSON Data from API Using Golang

This article guides you on how to retrieve JSON data from an API using the Golang programming language, helping you better understand how to interact with web services.
How to DELETE data from a MySQL database using Golang

A guide on how to connect and delete data from a table in a MySQL database using the Golang programming language.
How to INSERT data into a MySQL database using Golang

A guide on how to use Prepared Statements in Golang to insert data into a MySQL database with multiple parameters.
How to Post Data to API Using Golang

This article guides you on how to send data to an API using the POST method in Golang, helping you better understand how to interact with web services.
How to open the Notepad application using Golang

A guide on how to use the `os/exec` package in Golang to open the Notepad application on Windows. This is a practical example of how to call and run external programs from a Go program.
Slices in Golang: Usage and examples

This article explains how to work with slices in Golang, including how to declare, access, and manipulate slices—a flexible way to handle arrays more efficiently in Go.

main.add_cart_success