Golang Multipart File Upload Using Form File

Golang File Upload using FormFile

In this blog, we will learn about Golang Multipart File Upload using Form File.

Uploading Files on the server is useful in many scenarios like uploading your resume on a job portal, uploading your picture on any website or social media.

HTML Template for Uploading File

In this example, we are using bootstrap starter code for the designing of the template.

Learn how to parse templates in Golang.

<form action="/upload" method="POST" class="form-group" enctype="multipart/form-data">
        <label for="file">File :</label>
        <input type="file" name="file" id="file">
        <input type="submit" value="Upload File" name="submit" class="btn btn-success">
Golang Upload File
Golang Upload file

Upload File in Golang

Create fileupload.go file, we will define all the handlers and routes in this Go file.

Parsing HTML Templates

First of all the HTML template for file uploading will be parsed and will be executed for the "/" route.

var parsedTemplate *template.Template

func init() {
	parsedTemplate, _ = template.ParseFiles("template/index.html")

func index(w http.ResponseWriter, r *http.Request) {
	parsedTemplate.Execute(w, nil)

Multipart File Upload Function

func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseMultipartForm(10 << 20)
	file, header, err := r.FormFile("file")
	if err != nil {
		log.Println("Error Getting File", err)
	defer file.Close()

	out, pathError := ioutil.TempFile("temp-images", "upload-*.png")
	if pathError != nil {
		log.Println("Error Creating a file for writing", pathError)
	defer out.Close()

	_, copyError := io.Copy(out, file)
	if copyError != nil {
		log.Println("Error copying", copyError)
	fmt.Fprintln(w, "File Uploaded Successfully! ")
	fmt.Fprintln(w, "Name of the File: ", header.Filename)
	fmt.Fprintln(w, "Size of the File: ", header.Size)
Golang File Upload
Golang File Upload

First of all, we set the limit for the size of the file to be uploaded on the server using the ParseMultipartForm function from the request parameter.

Then FormFile handler is called on the HTTP request to get the file that is uploaded. The defer statement closes the file once the function returns.

when the uploaded file is received we need to store it somewhere so a temporary folder is created, the file name is preceded by “upload-” and the extension for the file is “.png”. If there occurs any kind of error while folder creation the error is logged out and the function returns without going further.

After that, we copy the uploaded file to the path created.

When all this process is completed and no error occurs, we print a success message along with the details of the file to the web page.

Learn more about Golang Multipart File Upload using Form File from Golang.org.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *