blog/internal/controller/FileController.go

42 lines
1.0 KiB
Go

package controller
import (
"blog/internal/model/AjaxResult"
"blog/internal/service"
"net/http"
"net/url"
"strconv"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"github.com/kataras/iris/v12/sessions"
)
type FileController struct {
Ctx iris.Context
Session *sessions.Session
}
func (ctrl *FileController) ViewFile() {
id := ctrl.Ctx.Params().Get("id")
file, err := service.FileService.GetFile(id)
if err != nil || file.Id == "" {
ctrl.Ctx.JSON(AjaxResult.Error("文件不存在"))
return
}
ctrl.Ctx.Header("Content-Disposition", "attachment;filename="+url.QueryEscape(file.FileName))
if file.FileSize != 0 {
ctrl.Ctx.Header("Content-Length", strconv.FormatInt(file.FileSize, 10))
}
ctrl.Ctx.Write(file.Data)
}
func (ctrl *FileController) BeforeActivation(activation mvc.BeforeActivation) {
// log.Println("before")
activation.Handle(http.MethodGet, "{id}", "ViewFile")
}
func (ctrl *FileController) AfterActivation(activation mvc.AfterActivation) {
// log.Println("after")
}