[golang]简单文件上传服务

时间:2025-03-03 06:58:48

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

package main

import (
    "fmt"
    "/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 , r *) {
    ([]byte(uploadHTML))
}

func upload(w , r *) {
    if  == "GET" {
        index(w, r)
        return
    }

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

    localpath := ("%s%s", destLocalPath, )
    localfd, err := (localpath, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        (err)
        ([]byte("upload failed."))
        return
    }
    defer ()

    (localfd, clientfd)
    ([]byte("upload finish."))
}

func newRouter()  {
    hdl := ()
    ("/", upload)

    return hdl
}

func main() {
    (":8877", newRouter())
}

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

package main

import (
    "crypto/sha1"
    "encoding/hex"
    "fmt"
    "/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 , r *) {
    ([]byte(uploadHTML))
}

func upload(w , r *) {
    if  == "GET" {
        index(w, r)
        return
    }

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

    localpath := ("%s%s", destLocalPath, )
    localfd, err := (localpath, os.O_WRONLY|os.O_CREATE, 0666)
    if err != nil {
        (err)
        ([]byte("upload failed."))
        return
    }
    defer ()

    // 利用在读取文件内容时计算hash值
    fhash := ()
    (localfd, (clientfd, fhash))
    hstr := ((nil))
    ([]byte(("upload finish:%s", hstr)))
}

func newRouter()  {
    hdl := ()
    ("/", upload)

    return hdl
}

func main() {
    (":8877", newRouter())
}