3.文件上传
最后更新于:2022-04-02 04:53:55
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
~~~
~~~
admin/user/add
this is admin/user/add
~~~
';