新建一个controller 实现对文件的获取并保存功能
package controllers
import (
"github.com/astaxie/beego"
"fmt"
"strings"
)
type Demo3Controller struct {
beego.Controller
}
func (this *Demo3Controller)Getfile(){
this.TplName="upfile.html"
}
func (this *Demo3Controller)Postfile(){
file, header, e := this.GetFile("file")
defer file.Close()
if e!=nil{
this.Ctx.WriteString("文件上传失败!"+fmt.Sprint(e))
}else {
headers := strings.Split(header.Filename, "\\")
err := this.SaveToFile("file", "static"+"/"+headers[len(headers)-1])
if err!=nil{
this.Ctx.WriteString("文件保存失败!"+fmt.Sprint(err))
}else {
this.Ctx.WriteString("文件保存成功!")
}
}
}
注册路由,当浏览器访问这个地址时,执行相应函数下的方法
beego.Router("/getfile",&controllers.Demo3Controller{},"Get:Getfile;Post:Postfile")
访问浏览器时获取这个页面 ,并让其提交文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="submit">
</form>
</body>
</html>