Beego脱坑(十一)文件上传、下载

创建模板
先创建一个模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload"  enctype="multipart/form-data"  method="post">
    <input type="file" name ="file">
    <input type="submit" value="上传">
</form>
</body>
</html>

文件上传
package controllers
 
import "github.com/astaxie/beego"
 
type UploadController struct {
    beego.Controller
}
 
func (this *UploadController) Get() {
 
    this.TplName="Upload.html"
}
 
func (this *UploadController)Post()  {
    file,head,err:=this.GetFile("file")
    if err!=nil {
        this.Ctx.WriteString("获取文件失败")
        return
    }
    defer file.Close()
 
    filename:=head.Filename
    err =this.SaveToFile("file","static/"+filename)
    if err!=nil {
        this.Ctx.WriteString("上传失败1")
    }else {
        this.Ctx.WriteString("上传成功")
    }
}
注意:GetFile函数的参数和SaveToFile函数的第一个参数需要和标签中name属性相同。

GetFile该方法主要用于用户读取表单中的文件名,然后返回相应的信息。 GetFile返回三个参数:文件、文件信息头、错误。

我们可以使用head.Filename 获取文件名 head.Size获取文件大小等。

SaveToFile该方法是在GetFile的基础上实现了快速保存的功能

文件下载
//下载文件
type FileOptDownloadController struct {
    beego.Controller
}
func (this *FileOptDownloadController) Get() { 
 
    //第一个参数是文件的地址,第二个参数是下载显示的文件的名称
    this.Ctx.Output.Download("static/img/1.jpg","1.jpg")
}

发布了76 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43778179/article/details/104723276