前端頁面form表單
<form action="/fileupload/upload" method="post" enctype="multipart/form-data"> <input type="file" name="fileupload" /><br> <input type="submit" value="上傳" /> </form>
注意:實現文件上傳的時候,form表單必須有enctype="multipart/form-data"屬性;
可以自己設置上傳文件的限制條件(文件大小,類型等)
控制器代碼
//接收文件流並存儲到本地 func (c *FileUploadController) FileHandler() { //獲取上傳的文件 file, head, _ := c.GetFile("fileupload") ext := path.Ext(head.Filename) //限制上傳文件類型 var FileAllow map[string]bool = map[string]bool{ ".jpg": true, ".txt": true, ".png": true, ".go": true, } if _, ok := FileAllow[ext]; !ok { c.Ctx.WriteString("文件后綴名不符合上傳要求") return } defer file.Close() err:=c.SaveToFile("fileupload","static/upload/"+head.Filename) if err != nil { c.Ctx.WriteString("上傳文件失敗") } c.Ctx.WriteString("上傳文件成功") }
可以根據需求設置文件大小和文件后綴名。
需要自己設置路由