Go文件上傳的例子

直接上代碼:
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("./test/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
        if err != nil {
            fmt.Println(err)
            return
        }
        defer f.Close()
        io.Copy(f, file)
    }
}

func main() {
    http.HandleFunc("/", upload)
    err := http.ListenAndServe(":9000", nil)
    if err != nil {
        fmt.Println("error:", err)
    }

}
upload.gtpl文件如下
<html>
<head>
<title>上傳文件</title>
</head>
<form enctype="multipart/form-data" action="http://127.0.0.1:9000/upload" method="post">
<input type="file" name="uploadfile" />
<input type="hidden" name="toke" value="``.``"/>
<input type="submit" value="upload">
</form>
</body>
</html>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章