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)
        }
    }
    人生短,迷茫路一程又一程。 脚步重,雨雪天踟蹰也踟蹰。 滴水聚,久无成效伊人不见。 该如何,敲击敲击昼夜不停。
  • 相关阅读:
    实反对称矩阵正则化
    小矩阵相乘效率对比:lapack, cblas, 手写函数
    python实现: VMC做一维谐振子
    一个简单矩阵的本征值问题
    python画能级图
    广义相对论笔记
    PVPC kb3g pn/upn Ti44 LAP 脚本
    自组织临界现象:沙堆模型
    c#备份MySQL数据库 转载 from
    vs2010 新特性 from
  • 原文地址:https://www.cnblogs.com/DesignerA/p/11570881.html
Copyright © 2011-2022 走看看