实现方法

Beego 在controller处理上提供了GetFile和GetFiles方法,以获取MultipartForm里的文件内容。详细说明查看godoc

获取单个文件 func (*Controller) GetFile

func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) GetFile returns the file data in file upload field named as key. it returns the first one of multi-uploaded files.

获取多个文件 func (*Controller) GetFiles

func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error)

本文结合示例代码和工程应用提供实际可用解决方法。 前端页面上传的请求格式按照rfc1867标准即可。 Body内容如下图所示

服务端代码

import(
	"io"
	"os"
	"strings"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

//默认参数
const (
    STATIC_PATH = "tmp/"
)

//	文件信息格式
type FileRecord struct {
	FileName   string `json:"file_name"`
	Path       string `json:"path"`
	FileSize   string `json:"file_size"`
	UploadTime string `json:"upload_time"`
}


//	上传
type UploadController struct {
	beego.Controller
}

func (c UploadController) Post() {

	//跨域检查
	//访问控制
	//权限控制

	//文件保存
	files, err := c.GetFiles("file")
	if err != nil {
		c.Ctx.WriteString(common.RespError("00001", "Invalid file"))
		return
	}
	var fileRecords []FileRecord

	for i, _ := range files {
		//文件后缀过滤
		suffixIndex := strings.LastIndex(files[i].Filename, ".")
		if !strings.Contains(".doc/.docx/.xls/.xlsx/.zip/.rar ", files[i].Filename[suffixIndex:]) {
			c.Ctx.WriteString(RespError("00001", "only support .doc/.docx/.xls/.xlsx/.zip/.rar file"))
			return
		}

		var fpath string = ""
		fpath = STATIC_PATH + files[i].Filename + fmt.Sprint("_", time.Now().Unix())

		var record troublesheet.FileRecord

		//获取文件句柄
		hFile, err := files[i].Open()
		if err != nil {
			c.Ctx.WriteString(RespError("00001", "failed to upload ["+files[i].Filename+"]"))
			return
		}

		//获取文件大小
		err, fSize := common.File_GetSize(hFile)
		if err != nil {
			logs.Debug("failed to upload [" + files[i].Filename + "],reason: errors on server file system,failed to get file size ")
			c.Ctx.WriteString(RespError("00001", "failed to upload ["+files[i].Filename+"],reason: unrecognized file"))
			return
		}

		//创建本地文件
		destFile, err := os.Create(fpath)
		if err != nil {
			logs.Debug("failed to upload [" + files[i].Filename + "],reason: errors on server file system,failed to create local path ")
			c.Ctx.WriteString(RespError("00001", "failed to upload ["+files[i].Filename+"],reason: errors on server file system "))
			return
		}

		//文件保存
		_, err = io.Copy(destFile, hFile)
		if err != nil {
			logs.Debug("failed to upload [" + files[i].Filename + "],reason: errors on server file system,failed to store source files ")
			c.Ctx.WriteString(RespError("00001", "failed to upload ["+files[i].Filename+"],reason: errors on server file system "))
			return
		}

		record.FileName = files[i].Filename
		record.Path = fpath
		record.FileSize = fmt.Sprint(fSize)
		record.UploadTime = time.Now().Format("2006-01-02 15:04:05")

		hFile.Close()
		destFile.Close()

		fileRecords = append(fileRecords, record)
	}
	c.Ctx.WriteString(RespData(nil, fileRecords))
	return
}

返回结果

{
  "errcode": "00000",
  "data": null,
  "datas": [
	  {
      "file_name": "template_1512742894.xlsx",
      "path": "/data/file/workflow/trouble/template_1512742894.xlsx_1514342635",
      "file_size": "11168",
      "upload_time": "2017-12-27 10:43:55"
    }
  ]
}

文章目录