作者 yangfu

文件下载

package v1
import (
"fmt"
"github.com/astaxie/beego"
"opp/controllers"
"opp/internal/utils"
"opp/protocol"
"path/filepath"
"strings"
)
type FileController struct {
controllers.BaseController
}
// DownLoad
// @router /opp/file [post]
func (this *FileController) DownLoad() {
var (
msg *protocol.ResponseMessage
err error
rsp *protocol.FileResponse = &protocol.FileResponse{}
)
defer func() {
if msg.Errno != 0 {
this.Resp(msg)
}
}()
fileUrl := this.Ctx.Request.RequestURI
filePath := strings.Replace(fileUrl, "/file/opp", "", 1)
filePath = filepath.Join(beego.AppConfig.String("source_path"), filePath)
if utils.Exists(filePath) {
this.Ctx.Output.Download(filePath)
} else {
err = protocol.NewCustomMessage(0, fmt.Sprintf("文件不存在:%v", filePath))
}
msg = protocol.NewReturnResponse(rsp, err)
}
... ...
package utils
import "os"
// 判断所给路径文件/文件夹是否存在
func Exists(path string) bool {
_, err := os.Stat(path) //os.Stat获取文件信息
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
// 判断所给路径是否为文件夹
func IsDir(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
return s.IsDir()
}
// 判断所给路径是否为文件
func IsFile(path string) bool {
return !IsDir(path)
}
... ...
... ... @@ -287,6 +287,14 @@ func init() {
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:FileController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:FileController"],
beego.ControllerComments{
Method: "DownLoad",
Router: `/opp/file`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:MessageController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:MessageController"],
beego.ControllerComments{
Method: "AnnouncementRead",
... ...
... ... @@ -33,7 +33,9 @@ func init() {
nsH5 := beego.NewNamespace("h5", beego.NSBefore(controllers.LogRequestData), beego.NSBefore(controllers.AllowOption), beego.NSInclude(&controllers.H5Controller{}))
beego.AddNamespace(nsH5)
//post 下载文件
beego.Router("/file/opp/*", &v1.FileController{}, "post:DownLoad")
//get 直接获取文件
beego.SetStaticPath("/file/opp", beego.AppConfig.String("source_path"))
beego.SetStaticPath("/log", beego.AppConfig.String("aliyun_logs_access"))
beego.Handler("/metrics", promhttp.Handler())
... ...
... ... @@ -67,7 +67,7 @@ func UploadFile(request *protocol.FileRequest) (rsp *protocol.FileResponse, err
return
}
}
virtualPath = beego.AppConfig.String("source_host") + filepath.Join(virtualPath, request.FileType, date)
virtualPath = fmt.Sprintf("%v%v/%v/%v", beego.AppConfig.String("source_host"), virtualPath, request.FileType, date)
for i := range request.Files {
f := request.Files[i]
prefix := fmt.Sprintf("%v_%v", time.Now().Unix(), common.RandomString(32))
... ...