Golang实现Web文件上传
jopen
10年前
// fileUpload project main.go package main import ( "fmt" "html/template" "io" "log" "net/http" "os" ) var buf []byte func upload(w http.ResponseWriter, r *http.Request) { r.ParseForm() if r.Method == "GET" { t, err := template.ParseFiles("upload.gptl") checkErr(err) t.Execute(w, nil) } else { file, handle, err := r.FormFile("file") checkErr(err) f, err := os.OpenFile("./test/"+handle.Filename, os.O_WRONLY|os.O_CREATE, 0666) io.Copy(f, file) checkErr(err) defer f.Close() defer file.Close() fmt.Println("upload success") } } func checkErr(err error) { if err != nil { err.Error() } } func main() { http.HandleFunc("/upload", upload) err := http.ListenAndServe(":8888", nil) if err != nil { log.Fatal("listenAndServe: ", err) } }
最主要的其实也就是这两句:
f, err := os.OpenFile("./test/"+handle.Filename, os.O_WRONLY|os.O_CREATE, 0666) io.Copy(f, file)
执行目录,权限,然后执行copy
upload.gptl文件:
<html> <head></head> <body> <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" value="" /> <input type="submit" name="submit" /> </form> </body> </html>
如果当前目录下没有test文件夹,不会自动创建。需要手动创建
来自:http://my.oschina.net/0x4ad/blog/378209