beego 点滴

时间:2022-05-07 14:49:44

在使用beego时遇到 need a primary key field

1 确保结构中的 字段首字母大写
2 beego默认主键是id 如果主键定义的是其他字段比如userid 那么加上orm pk type User struct {
Id int `orm:"pk;column(Userid);"`
Name string
}

 beego 上传文件

package main

import (
"github.com/astaxie/beego"
) type UploadController struct {
beego.Controller
}
func (this *UploadController) Post() {
this.SaveToFile("uploadfile", "./static/files/",true)
this.Ctx.Redirect(, "/upload") }
/*
* fromfile input type=file name=fromfile
* tofilepath the path where the file going to save
* newfilename boolen is create new name or use original name
*/
func (c *UploadController) SaveToFile(fromfile, tofilepath string, newfilename bool) error {
file, h, err := c.Ctx.Request.FormFile(fromfile)
if err != nil {
return err
}
defer file.Close()
newname := h.Filename
if newfilename {
newname = fmt.Sprintf("%v%s", time.Now().Unix(), path.Ext(h.Filename))
}
tofilepath = path.Join(tofilepath, newname)
f, err := os.OpenFile(tofilepath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, )
if err != nil {
return err
}
defer f.Close()
io.Copy(f, file)
return nil
}
func main() {
  beego.Router("/upload", &UploadController{}) beego.Run()
}
<head>
<title>上传文件</title>
</head>
<body> <form enctype="multipart/form-data" action="/upload" method="post">
<input type="file" name="uploadfile" />
<input type="submit" value="upload" />
</form> </body>
</html>