beego上传文件

一:核心方法概况:

html代码:

1

2

3

4

<form id="fform" method="POST" enctype="multipart/form-data">   

    <input id="myfile" name="myfile" type="file" />  

    <input type="submit" value="保存"  />

form>

 

beego代码:

1

2

3

4

5

6

func (this *ServiceController) Upload() {  

    f, h, _ := this.GetFile("myfile")                  //获取上传的文件

    path := SDPATH + h.Filename               //文件目录

    f.Close()                                          //关闭上传的文件,不然的话会出现临时文件不能清除的情况

    this.SaveToFile("myfile", path)                    //存文件   

}

 

 

二、扩展方法

 

package controllers
import (
    "path"
    "crypto/md5"
    "time"
    "fmt"
    "github.com/astaxie/beego"
    "math/rand"
    "os"
)
type UploadController struct{
    beego.Controller 
}

func (this *UploadController) UpForm(){
    this.TplName = "upload.tpl"
}

func (this *UploadController) UpFile(){

    f, h, _ := this.GetFile("myfile")//获取上传的文件
    ext := path.Ext(h.Filename)
    //验证后缀名是否符合要求
    var AllowExtMap map[string]bool = map[string]bool{
        ".jpg":true,
        ".jpeg":true,
        ".png":true,
    }
    if _,ok:=AllowExtMap[ext];!ok{
        this.Ctx.WriteString( "后缀名不符合上传要求" )
        return 
    }
    //创建目录
    uploadDir := "static/upload/" + time.Now().Format("2006/01/02/")
    err := os.MkdirAll( uploadDir , 777)
    if err != nil {
        this.Ctx.WriteString( fmt.Sprintf("%v",err) )
        return 
    }
    //构造文件名称
    rand.Seed(time.Now().UnixNano())
    randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000 )
    hashName := md5.Sum( []byte( time.Now().Format("2006_01_02_15_04_05_") + randNum ) )

    fileName := fmt.Sprintf("%x",hashName) + ext
    //this.Ctx.WriteString(  fileName )

    fpath := uploadDir + fileName
    defer f.Close()//关闭上传的文件,不然的话会出现临时文件不能清除的情况
    err = this.SaveToFile("myfile", fpath)
    if err != nil {
        this.Ctx.WriteString( fmt.Sprintf("%v",err) )
    }
    this.Ctx.WriteString( "上传成功~!!!!!!!" )
}

 

 

 

你可能感兴趣的:(Go语言)