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")
}


作者:Clown95
来源:CSDN
原文:https://blog.csdn.net/yang731227/article/details/82288542
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/qq_33249452/article/details/89680204