-
-
Save networkextension/7d6b10bbd772071eee6b794a028b804a to your computer and use it in GitHub Desktop.
Upload File - golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/md5" | |
"fmt" | |
"io" | |
"net/http" | |
"os" | |
"strconv" | |
"text/template" | |
"time" | |
) | |
func main() { | |
http.HandleFunc("/upload", upload) | |
http.ListenAndServe(":8000", nil) | |
} | |
func upload(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("method:", r.Method) | |
if r.Method == "GET" { | |
crutime := time.Now().Unix() | |
h := md5.New() | |
io.WriteString(h, strconv.FormatInt(crutime, 10)) | |
token := fmt.Sprintf("%x", h.Sum(nil)) | |
t, _ := template.ParseFiles("upload.gtpl") | |
t.Execute(w, token) | |
} else { | |
r.ParseMultipartForm(32 << 20) | |
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("./"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer f.Close() | |
io.Copy(f, file) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment