使用beego框架進行檔案上傳
摘要:
模板程式碼如下
<form id="fform" method="POST" enctype="multipart/form-data" action="/upload">
<input id=...
模板程式碼如下
<form id="fform" method="POST" enctype="multipart/form-data" action="/upload"> <input id="myfile" name="myfile" type="file" /> <input type="submit" value="儲存"/> </form>
上傳程式碼實現如下
package controllers import ( "path" "crypto/md5" "time" "fmt" "github.com/astaxie/beego" "math/rand" "os" ) type UploadController struct{ beego.Controller } func (this *UploadController) UpForm(){ this.TplName = "upload.tpl" } func (this *UploadController) UpFile(){ f, h, _ := this.GetFile("myfile")//獲取上傳的檔案 ext := path.Ext(h.Filename) //驗證字尾名是否符合要求 var AllowExtMap map[string]bool = map[string]bool{ ".jpg":true, ".jpeg":true, ".png":true, } if _,ok:=AllowExtMap[ext];!ok{ this.Ctx.WriteString( "字尾名不符合上傳要求" ) return } //建立目錄 uploadDir := "static/upload/" + time.Now().Format("2006/01/02/") err := os.MkdirAll( uploadDir , 777) if err != nil { this.Ctx.WriteString( fmt.Sprintf("%v",err) ) return } //構造檔名稱 rand.Seed(time.Now().UnixNano()) randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000 ) hashName := md5.Sum( []byte( time.Now().Format("2006_01_02_15_04_05_") + randNum ) ) fileName := fmt.Sprintf("%x",hashName) + ext //this.Ctx.WriteString(fileName ) fpath := uploadDir + fileName defer f.Close()//關閉上傳的檔案,不然的話會出現臨時檔案不能清除的情況 err = this.SaveToFile("myfile", fpath) if err != nil { this.Ctx.WriteString( fmt.Sprintf("%v",err) ) } this.Ctx.WriteString( "上傳成功~!!!!!!!" ) }