Skip to content

Instantly share code, notes, and snippets.

@sanatgersappa
Created March 10, 2013 06:02
Show Gist options
  • Save sanatgersappa/5127317 to your computer and use it in GitHub Desktop.
Save sanatgersappa/5127317 to your computer and use it in GitHub Desktop.
Web app written in Go to demonstrate handling multiple file uploads.
package main
import (
"html/template"
"io"
"net/http"
"os"
)
//Compile templates on start
var templates = template.Must(template.ParseFiles("tmpl/upload.html"))
//Display the named template
func display(w http.ResponseWriter, tmpl string, data interface{}) {
templates.ExecuteTemplate(w, tmpl+".html", data)
}
//This is where the action happens.
func uploadHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
//GET displays the upload form.
case "GET":
display(w, "upload", nil)
//POST takes the uploaded file(s) and saves it to disk.
case "POST":
//parse the multipart form in the request
err := r.ParseMultipartForm(100000)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//get a ref to the parsed multipart form
m := r.MultipartForm
//get the *fileheaders
files := m.File["myfiles"]
for i, _ := range files {
//for each fileheader, get a handle to the actual file
file, err := files[i].Open()
defer file.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//create destination file making sure the path is writeable.
dst, err := os.Create("/home/sanat/" + files[i].Filename)
defer dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//copy the uploaded file to the destination file
if _, err := io.Copy(dst, file); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
//display success message.
display(w, "upload", "Upload successful.")
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func main() {
http.HandleFunc("/upload", uploadHandler)
//static file handler.
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
//Listen on port 8080
http.ListenAndServe(":8080", nil)
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload Demo</title>
<link type="text/css" rel="stylesheet" href="/assets/css/style.css" />
</head>
<body>
<div class="container">
<h1>File Upload Demo</h1>
<div class="message">{{.}}</div>
<form class="form-signin" method="post" action="/upload" enctype="multipart/form-data">
<fieldset>
<input type="file" name="myfiles" id="myfiles" multiple="multiple">
<input type="submit" name="submit" value="Submit">
</fieldset>
</form>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment