Golang Tutorial – How to process file uploads in Go

File Upload with Golang

Processing user-uploaded files is a common task in web development, and you’ll likely need to develop a service that handles this task from time to time. This article will guide you through running file uploads on a Golang web server and discuss standard requirements such as multiple file uploads, progress reporting, and restricting file sizes.

This tutorial will look at file uploads in Golang

and cover standard requirements such as setting size limits, file type restrictions, and progress reporting. You can find the complete source code for this tutorial on GitHub.

Getting started

Clone this repository to your computer and cd into the created directory. You’ll see a main.go file that contains the following code: main.go

package main

import (
	"log"
	"net/http"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "text/html")
	http.ServeFile(w, r, "index.html")
}

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

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", indexHandler)
	mux.HandleFunc("/upload", uploadHandler)

	if err := http.ListenAndServe(":4500", mux); err != nil {
		log.Fatal(err)
	}
}

copy

The code is used to start a server on port 4500 and render the index.html file on the root route. In the index.html file, we have a form containing a file input that posts to an /upload route on the server.index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>File upload demo</title>
  </head>
  <body>
    <form
      id="form"
      enctype="multipart/form-data"
      action="/upload"
      method="POST"
    >
      <input class="input file-input" type="file" name="file" multiple />
      <button class="button" type="submit">Submit</button>
    </form>
  </body>
</html>

copy

Let’s go ahead and write the code we need to process file uploads from the browser.

Set the maximum file size in Golang

It’s necessary to restrict the maximum size of file uploads to avoid a situation where clients accidentally or maliciously upload gigantic files and end up wasting server resources. In this section, we’ll set a maximum upload limit of One Megabyte and show an error if the uploaded file exceeds the limit.

A common approach is to check the Content-Length request header and compare it to the maximum file size allowed to see if it’s exceeded or not.

if r.ContentLength > MAX_UPLOAD_SIZE {
	http.Error(w, "The uploaded image is too big. Please use an image less than 1MB in size", http.StatusBadRequest)
	return
}

copy

I don’t recommend using this method because the Content-Length header can be modified on the client to be any value regardless of the actual file size. It’s better to rely on the http.MaxBytesReader method is demonstrated below. Update your main.go file with the highlighted portion of the following snippet:


There is no ads to display, Please add some