本文實(shí)例講述了golang簡(jiǎn)單獲取上傳文件大小的方法。分享給大家供大家參考,具體如下:
復(fù)制代碼 代碼如下:
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
}
// 上傳頁(yè)面
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)
}
}
希望本文所述對(duì)大家Go語(yǔ)言程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- golang實(shí)現(xiàn)的文件上傳下載小工具
- golang語(yǔ)言實(shí)現(xiàn)的文件上傳與文件下載功能示例
- Golang實(shí)現(xiàn)異步上傳文件支持進(jìn)度條查詢(xún)的方法
- Golang+Android基于HttpURLConnection實(shí)現(xiàn)的文件上傳功能示例
- Golang實(shí)現(xiàn)http文件上傳小功能的案例