功能很簡單,代碼也很簡潔,這里就不多廢話了。
package main
import (
"fmt"
"io"
"net/http"
"os"
)
const (
upload_path string = "./upload/"
)
func helloHandle(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello world!")
}
//上傳
func uploadHandle(w http.ResponseWriter, r *http.Request) {
//從請求當中判斷方法
if r.Method == "GET" {
io.WriteString(w, "<html><head><title>我的第一個頁面</title></head><body><form action='' method=\"post\" enctype=\"multipart/form-data\"><label>上傳圖片</label><input type=\"file\" name='file' /><br/><label><input type=\"submit\" value=\"上傳圖片\"/></label></form></body></html>")
} else {
//獲取文件內(nèi)容 要這樣獲取
file, head, err := r.FormFile("file")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
//創(chuàng)建文件
fW, err := os.Create(upload_path + head.Filename)
if err != nil {
fmt.Println("文件創(chuàng)建失敗")
return
}
defer fW.Close()
_, err = io.Copy(fW, file)
if err != nil {
fmt.Println("文件保存失敗")
return
}
//io.WriteString(w, head.Filename+" 保存成功")
http.Redirect(w, r, "/hello", http.StatusFound)
//io.WriteString(w, head.Filename)
}
}
func main() {
//啟動一個http 服務器
http.HandleFunc("/hello", helloHandle)
//上傳
http.HandleFunc("/image", uploadHandle)
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("服務器啟動失敗")
return
}
fmt.Println("服務器啟動成功")
}
以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡,能夠?qū)Υ蠹覍W習go語言有所幫助。