zoukankan      html  css  js  c++  java
  • 使用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)
        }
    }
    人生短,迷茫路一程又一程。 脚步重,雨雪天踟蹰也踟蹰。 滴水聚,久无成效伊人不见。 该如何,敲击敲击昼夜不停。
  • 相关阅读:
    Fractions Again?! UVA
    Maximum Product UVA
    Investigating Div-Sum Property UVA
    Period UVALive
    Numbers That Count POJ
    Orders POJ
    小明的数列
    Spreading the Wealth uva 11300
    Play on Words UVA
    第二百七十天 how can I 坚持
  • 原文地址:https://www.cnblogs.com/DesignerA/p/11570881.html
Copyright © 2011-2022 走看看