~~~
<form action="/upload" method="post" enctype="multipart/form-data">
上传文件:<input type="file" name="upload_file">
<input type="submit" value="提交">
</form>
package users001
import (
"fmt"
"github.com/astaxie/beego"
"strconv"
"time"
)
type UploadController struct {
beego.Controller
}
func (c *UploadController) Get() {
c.TplName = "users001/upload.html"
}
func (u *UploadController) Post() {
// 获取上传的文件
f, h, err := u.GetFile("upload_file")
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
// 生成时间戳,防止重名
timeUnix := time.Now().Unix() // int64类型
time_str := strconv.FormatInt(timeUnix, 10) // 将int64转为字符串 convert:转换
// 保存获取到的文件
err1 := u.SaveToFile("upload_file", "static/upload/"+time_str+h.Filename) // 这里必须有这个路径才会保存成功, 否则报错:The system cannot find the path specified
if err1 != nil {
fmt.Println(err1)
}
u.TplName = "index.tpl"
}
~~~