golang简单获取上传文件大小的实现代码
本文实例讲述了golang简单获取上传文件大小的方法。分享给大家供大家参考,具体如下:
代码如下:
package main import ( "fmt" "io" "net/http" "log" "os" ) // 获取文件大小的接口 type Size interface { Size() int64 } // 获取文件信息的接口 type Stat interface { Stat() (os.FileInfo, error) } // hello world, the web server func HelloServer(w http.ResponseWriter, r *http.Request) { if "POST" == r.Method { file, _, err := r.FormFile("userfile") if err != nil { http.Error(w, err.Error(), 500) return } if statInterface, ok := file.(Stat); ok { fileInfo, _ := statInterface.Stat() fmt.Fprintf(w, "上传文件的大小为: %d", fileInfo.Size()) } if sizeInterface, ok := file.(Size); ok { fmt.Fprintf(w, "上传文件的大小为: %d", sizeInterface.Size()) } return } // 上传页面 w.Header().Add("Content-Type", "text/html") w.WriteHeader(200) html := ` <form enctype="multipart/form-data" action="/hello" method="POST"> Send this file: <input name="userfile" type="file" /> <input type="submit" value="Send File" /> </form> ` io.WriteString(w, html) } func main() { http.HandleFunc("/hello", HelloServer) err := http.ListenAndServe(":12345", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }
希望本文所述对大家Go语言程序设计有所帮助。
相关推荐
GoatSucker 2020-11-23
CoderToy 2020-11-16
蛰脚踝的天蝎 2020-11-10
ZGCdemo 2020-11-09
86193952 2020-10-27
Lzs 2020-10-23
hjr 2020-10-21
HELLOBOY 2020-10-21
qidiantianxia 2020-10-21
cmsmdn 2020-10-21
myspace 2020-10-21
笑面依旧 2020-10-21
专注前端开发 2020-10-21
技术之博大精深 2020-10-16
zhushenghan 2020-11-09
风雨断肠人 2020-10-13
xuguiyi00 2020-11-04
sichenglain 2020-10-27