1. 程式人生 > 實用技巧 >上傳單個檔案、上傳多個檔案

上傳單個檔案、上傳多個檔案

1、上傳單個文

views

beego 中 上 傳 圖 片 是 非 常 簡 單 的 , 但 是 要 注 意 的 是 form 表 單 中 必 須 加 入 enctype="multipart/form-data"這個屬性,否則你的瀏覽器不會傳輸你上傳的檔案。

article.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Article</title>
</head>

<body>
  <h2>上傳文章</h2>
  <form method="post" action="/article/doUpload" enctype="multipart/form-data">
    標題: <input type="text" name="title" />  <br><br>
    內容: <input type="text" name="content" />
    <br><br>

    檔案:<input type="file" name="pic" />
    <br><br>
    <input type="submit" value="提交">
  </form>
</body>

</html>

routers

package routers

import (
	"beegoupload/controllers"

	"github.com/astaxie/beego"
)

func init() {
	beego.Router("/", &controllers.MainController{})
	beego.Router("/focus", &controllers.FocusController{})
	beego.Router("/focus/doUpload", &controllers.FocusController{}, "post:DoUpload")
	beego.Router("/article", &controllers.ArticleController{})
	beego.Router("/article/doUpload", &controllers.ArticleController{}, "post:DoUpload")
}

controllers

GetFile 可以接受傳過來的圖片和檔案

package controllers

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

type ArticleController struct {
	beego.Controller
}

func (c *ArticleController) Get() {

	c.TplName = "article.html"
}

func (c *ArticleController) DoUpload() {

	title := c.GetString("title")
	content := c.GetString("content")
	beego.Info(title)
	beego.Info(content)
	//執行上傳檔案
	f, h, err := c.GetFile("pic")
	if err != nil {
		beego.Error(err)
		c.Ctx.WriteString("上傳檔案失敗")
		return
	}
	c.SaveToFile("pic", "static/upload/"+h.Filename) //目錄必須提前建立好

	//關閉檔案流
	defer f.Close()
	c.Ctx.WriteString("上傳檔案成功")
}

2、上傳多個檔案

focus.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Focus</title>
</head>

<body>  
  <h2>上傳輪播圖</h2>
  <form method="post" action="/focus/doUpload" enctype="multipart/form-data">

    標題: <input type="text" name="title" />
    <br><br>

    檔案1:<input type="file" name="pic1" /><br><br>

    檔案2:<input type="file" name="pic2" />
    <br><br>
    <input type="submit" value="提交">
  </form>
</body>

</html>

package controllers

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

type FocusController struct {
	beego.Controller
}

func (c *FocusController) Get() {
	c.TplName = "focus.html"
}

func (c *FocusController) DoUpload() {
	title := c.GetString("title")
	beego.Info(title)
	//接收第一個檔案
	f1, h1, err1 := c.GetFile("pic1")
	if err1 != nil {
		beego.Warning(err1)
	} else {
		//關閉檔案流
		defer f1.Close()
		c.SaveToFile("pic1", "static/upload/"+h1.Filename)
	}

	//接收第二個檔案

	f2, h2, err2 := c.GetFile("pic2")
	if err2 != nil {
		beego.Warning(err2)
	} else {
		defer f2.Close()
		c.SaveToFile("pic2", "static/upload/"+h2.Filename)
	}
	c.Ctx.WriteString("上傳檔案成功")

}