這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
// fileUpload project main.gopackage mainimport ( "fmt" "html/template" "io" "log" "net/http" "os")var buf []bytefunc 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檔案夾,不會自動建立。需要手動建立