beego 簡單的文件上傳下載功能


下載文件功能編寫html代碼上傳文件 提交走路由

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

  

編寫路由 入口到接收文件

package routers

import (
	"booktest/controllers"
	"github.com/astaxie/beego"
)

func init() {
    beego.Router("/files",&controllers.BookController{},"get:FileS")
    beego.Router("/filed",&controllers.BookController{},"post:FileD")

beego.Router("/get",&controllers.BookController{},"get:Get")
}

  

控制器代碼 可操作模型層

func (b *BookController) FileS()  {
	b.TplName="filed.html"
}

func (this *BookController) FileD()  {
	// 讀取文件信息
	f, h, err := this.GetFile("filename")

	if err != nil {
		log.Fatal("讀取文件錯誤", err)
	}

	// 延遲關閉文件
	defer f.Close()

    //查看文件可忽略 可保存文件以后在讀取
	data, err := ioutil.ReadAll(f)
	if err != nil {
		logs.Debug(err)
	}
	this.Ctx.WriteString(string(data))
	// 保存文件, 本地文件路徑static/upload/上傳文件名
	// 需要提前創建好static/upload目錄
	this.SaveToFile("filename", "static/upload/" + h.Filename)
}

func (this *BookController) Get() {
// 業務邏輯處理,例如先檢測用戶權限 

// 下載服務器上當前目錄/data/file.zip文件, 下載后的文件名為:壓縮包1.zip
this.Ctx.Output.Download("data/file.zip", "壓縮包1.zip")
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM