[golang]简单文件上传服务

利用net/http库及gorilla/mux库实现了一个简单的文件上传服务,
示例如下:

package main

import (
    "fmt"
    "github.com/gorilla/mux"
    "io"
    "net/http"
    "os"
)

const uploadHTML = `
<html>  
  <head>  
    <title>选择文件</title>
  </head>  
  <body>  
    <form enctype="multipart/form-data" action="/" method="post">  
      <input type="file" name="uploadfile" />  
      <input type="submit" value="上传文件" />  
    </form>  
  </body>  
</html>`

const destLocalPath = "/data/files/"

func index(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(uploadHTML))
}

func upload(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
        index(w, r)
        return
    }

    r.ParseMultipartForm(32 << 20) // max memory is set to 32MB
    clientfd, handler, err := r.FormFile("uploadfile")
    if err != nil {
        fmt.Println(err)
        w.Write([]byte("upload failed."))
        return
    }
    defer clientfd.Close()

    localpath := fmt.Sprintf("%s%s", destLocalPath, handler.Filename)
    localfd, err := os.OpenFile(localpath, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
        w.Write([]byte("upload failed."))
        return
    }
    defer localfd.Close()

    io.Copy(localfd, clientfd)
    w.Write([]byte("upload finish."))
}

func newRouter() http.Handler {
    hdl := mux.NewRouter()
    hdl.HandleFunc("/", upload)

    return hdl
}

func main() {
    http.ListenAndServe(":8877", newRouter())
}

假如需要在接收文件的时候计算文件hash值, 应该如何做呢?
根据io.TeeReader库,可以在文件上传过程中自动计算hash值, 完整代码修改为:

package main

import (
    "crypto/sha1"
    "encoding/hex"
    "fmt"
    "github.com/gorilla/mux"
    "io"
    "net/http"
    "os"
)

const uploadHTML = `
<html>  
  <head>  
    <title>选择文件</title>
  </head>  
  <body>  
    <form enctype="multipart/form-data" action="/" method="post">  
      <input type="file" name="uploadfile" />  
      <input type="submit" value="上传文件" />  
    </form>  
  </body>  
</html>`

const destLocalPath = "/data/files/"

func index(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(uploadHTML))
}

func upload(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
        index(w, r)
        return
    }

    r.ParseMultipartForm(32 << 20) // max memory is set to 32MB
    clientfd, handler, err := r.FormFile("uploadfile")
    if err != nil {
        fmt.Println(err)
        w.Write([]byte("upload failed."))
        return
    }
    defer clientfd.Close()

    localpath := fmt.Sprintf("%s%s", destLocalPath, handler.Filename)
    localfd, err := os.OpenFile(localpath, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        fmt.Println(err)
        w.Write([]byte("upload failed."))
        return
    }
    defer localfd.Close()

    // 利用io.TeeReader在读取文件内容时计算hash值
    fhash := sha1.New()
    io.Copy(localfd, io.TeeReader(clientfd, fhash))
    hstr := hex.EncodeToString(fhash.Sum(nil))
    w.Write([]byte(fmt.Sprintf("upload finish:%s", hstr)))
}

func newRouter() http.Handler {
    hdl := mux.NewRouter()
    hdl.HandleFunc("/", upload)

    return hdl
}

func main() {
    http.ListenAndServe(":8877", newRouter())
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值