使用go搭建一个简单的web服务器(6)处理文件上传

1.前端页面

<html>
<head>
上传文件
</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>

2.后端处理逻辑

package main

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

func upload(w http.ResponseWriter, r *http.Request) {
    fmt.Println("method:", r.Method)
    if r.Method == "GET" {
        //begin这里开始计算一个时间戳用于填充到模板中的隐藏标签中
        currenttime := time.Now().Unix()
        h := md5.New()
        io.WriteString(h, strconv.FormatInt(currenttime, 10))
        token := fmt.Sprintf("%x", h.Sum(nil))
        //end
        t, _ := template.ParseFiles("upload.html")
        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", upload)       //设置访问的路由
    err := http.ListenAndServe(":9090", nil) //设置监听的端口
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

 

posted @ 2019-09-23 10:26  DesignerA  阅读(882)  评论(0编辑  收藏  举报