利用net/http库及gorilla/mux库实现了一个简单的文件上传服务,
示例如下:
package mainimport ( "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 mainimport ( "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]简单文件上传服务所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)