Golang: Simple File Upload Using Go Languange


As a web programming language Go has capability to handle file upload from browser html form, in this post I will show you simple File Upload using Golang web programming.

  1. Create HTML Form upload src/webupload/upload.gtpl
    <html>
      <head>
             <title>Test Upload a File</title>
      </head>
      <body>
    <form enctype="multipart/form-data" action="http://127.0.0.1:9090/upload" method="post">
              {{/* 1. File input */}}
              <input type="file" name="uploadfile" />
    
              {{/* 2. Submit button */}}
              <input type="submit" value="upload file" />
          </form>
    
      </body>
      </html>
    
    

    1. GO Form
    *ignore unused token input
  2. Create go code to handle file upload src/webupload/upload.go
  3. package main
    
    import (
    	"crypto/md5"
    	"fmt"
    	"html/template"
    	"io"
    	"net/http"
    	"os"
    	"strconv"
    	"time"
    )
    
    func upload(w http.ResponseWriter, r *http.Request) {
    
    	if r.Method == "GET" {
    		// GET
    		t, _ := template.ParseFiles("upload.gtpl")
    
    		t.Execute(w, nil)
    
    	} else if r.Method == "POST" {
    		// Post
    		file, handler, err := r.FormFile("uploadfile")
    		if err != nil {
    			fmt.Println(err)
    			return
    		}
    		defer file.Close()
    
    		fmt.Fprintf(w, "%v", handler.Header)
    		f, err := os.OpenFile("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
    		if err != nil {
    			fmt.Println(err)
    			return
    		}
    		defer f.Close()
    
    		io.Copy(f, file)
    
    	} else {
    		fmt.Println("Unknown HTTP " + r.Method + "  Method")
    	}
    }
    
    func main() {
    	http.HandleFunc("/upload", upload)
    	http.ListenAndServe(":9090", nil) // setting listening port
    }
    
    
  4. Create new folder for upload destination src/webupload/testfolder
  5. that’s all

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s