1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| package main
import ( "crypto/md5" "fmt" "io" "log" "net/http" "os" "text/template" )
func main() { http.HandleFunc("/upload", upload) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } }
func upload(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { t, err := template.ParseFiles("./upload.html") if err != nil { log.Fatal(err) }
h := md5.New() token := fmt.Sprintf("%x", h.Sum(nil)) t.Execute(w, token) } else { r.ParseMultipartForm(32 << 20) f, fileHeader, err := r.FormFile("upload") if err != nil { log.Fatal(err) } defer f.Close()
fmt.Fprintf(w, "get upload file.") file, err := os.OpenFile("./"+fileHeader.Filename, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { log.Fatal(err) } defer file.Close()
io.Copy(file, f) } }
|