go web 第二天 学习笔记之文件上传

package main

import (
    "crypto/md5"
    "fmt"
    "html/template"
    "io"
    "log"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

func sayHelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()       //解析函数,默认是不会解析的
    fmt.Println(r.Form) //这些信息是输出到服务器端的打印信息
    fmt.Println("path", r.URL.Path)
    fmt.Println("scheme", r.URL.Scheme)
    fmt.Println(r.Form["url_long"])
    for k, v := range r.Form {
        fmt.Println("key:", k)
        fmt.Println("val:", strings.Join(v, "v"))
    }
    fmt.Fprintf(w, "Hello astaxie") //这个写入到w的是输出到客户端的
}
func login(w http.ResponseWriter, r *http.Request) {
    fmt.Println("login method:", r.Method) //获取请求的方法
    if r.Method == "GET" {
        t, e := template.ParseFiles("login.gtpl")
        crutime := time.Now().Unix()
        h := md5.New()
        io.WriteString(h, strconv.FormatInt(crutime, 10))
        token := fmt.Sprintf("%x", h.Sum(nil))
        fmt.Println("token:", token)
        //t, e := template.ParseFiles("login.gtpl")
        if e != nil {
            log.Fatal(e)
        }
        t.Execute(w, token)
    } else {
        r.ParseForm()
        //请求的是登录数据,那么执行登录的逻辑判断
        token := r.Form.Get("token")
        if token != "" {

        } else {

        }
        fmt.Println("username len:", len(r.Form["username"][0]))
        fmt.Println("username:", template.HTMLEscapeString(r.Form.Get("username"))) //输出到服务端
        fmt.Println("password", template.HTMLEscapeString(r.Form.Get("password")))
        template.HTMLEscape(w, []byte(r.Form.Get("username"))) //输出到客户端

    }
}
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("/", sayHelloName)       //设置访问的路由
    http.HandleFunc("/login", login)         //设置访问的路由
    http.HandleFunc("/upload", upload)       //设置访问的路由
    err := http.ListenAndServe(":9090", nil) //设置监听的端口
    if err != nil {
        log.Fatal("ListenAndServe", err)
    }

}
upload.gtpl
<html> <head> <title>文件上传</title> </head> <body> <form enctype="multipart/form-data" action="http://127.0.0.1:9090/upload" method="post"> <input type="file" name="uploadfile"/> <input type="hidden" name="token" value="{{.}}"/> <input type="submit" value="upload"/> </form> </body> </html>

如果当前目录下没有test文件夹,不会自动创建。需要手动创建