from表单文件上传: ~~~ |-- routers | `-- router.go ~~~ ~~~ package routers import ( admin "project/admin/controllers" "github.com/astaxie/beego" ) func init() { // 固定路由也就是全匹配的路由 beego.Router("/admin/user/index", &admin.UserController{}, "*:Index") beego.Router("/admin/user/add", &admin.UserController{}, "*:Add") } |-- admin | |--controllers | `-- user.go package admin import ( "path" "strings" "github.com/astaxie/beego" ) type UserController struct { beego.Controller } func (this *UserController) Index() { this.TplName = "admin/user/index.html" } func (this *UserController) Add() { if this.Ctx.Request.Method == "GET" { this.TplName = "admin/user/add.html" } else { //image,这是一个key值,对应的是html中input type-‘file’的name属性值 f, h, _ := this.GetFile("image") //得到文件的名称 fileName := h.Filename arr := strings.Split(fileName, ":") if len(arr) > 1 { index := len(arr) - 1 fileName = arr[index] } //关闭上传的文件,不然的话会出现临时文件不能清除的情况 f.Close() //保存文件到指定的位置 //static/img,这个是文件的地址,路径必须存在,第一个static前面不要有/ this.SaveToFile("image", path.Join("static/img/", fileName)) //跳转到 "admin/user/index.html" this.TplName = "admin/user/index.html" } } ~~~ ~~~ |-- views | |--admin | |--user | `-- add.html ~~~ ~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>admin/user/add</title> </head> <body> this is admin/user/add <form action='{{urlfor "UserController.Add"}}' method="post" enctype="multipart/form-data"> <div class="field-content"> 文件上传:<input name="image" type="file" /> </div> <div class="field-content"> <input type="submit" value="提交" /> </div> </form> </body> </html> ~~~