Go   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了[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())
}

假如需要在接收文件的时候@R_301_2183@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, 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("/",newRouter())
}

大佬总结

以上是大佬教程为你收集整理的[golang]简单文件上传服务全部内容,希望文章能够帮你解决[golang]简单文件上传服务所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。