github.com/SupenBysz/gf-admin-community@v0.7.4/sys_controller/common.go (about)

     1  package sys_controller
     2  
     3  import (
     4  	"context"
     5  	"github.com/SupenBysz/gf-admin-community/api_v1/sys_api"
     6  	"github.com/SupenBysz/gf-admin-community/sys_service"
     7  	"github.com/gogf/gf/v2/frame/g"
     8  	"github.com/gogf/gf/v2/os/gfile"
     9  )
    10  
    11  var Common = cCommon{}
    12  
    13  type cCommon struct{}
    14  
    15  // GetFile 获取图片文件,暴露此接口,
    16  func (c *cCommon) GetFile(ctx context.Context, req *sys_api.GetFileReq) (res *sys_api.UploadFileRes, err error) {
    17  
    18  	// 优先从缓存获取,缓存要是获取不到,那么从数据库加载文件信息,从而加载文件   缓存key == sign
    19  
    20  	file, err := sys_service.File().GetFile(ctx, req.Sign, req.Path, req.Id, req.CId)
    21  
    22  	if err != nil || file == nil {
    23  		// 渲染默认的图片
    24  		g.RequestFromCtx(ctx).Response.ServeFile("./resource/1x1_#00000000.png")
    25  		return nil, err
    26  	}
    27  
    28  	if gfile.GetContents(file.Src) != "" { // 本地文件访问路径
    29  		//  ServeFile 为响应提供文件 (通过给定文件路径path,ServeFile方法将会自动识别文件格式,如果是目录或者文本内容将会直接展示文件内容。如果path参数为目录,那么第二个参数allowIndex控制是否可以展示目录下的文件列表。)
    30  		g.RequestFromCtx(ctx).Response.ServeFile(file.Src) // 图片、文本文件txt、pdf也是直接输出、docs文档
    31  
    32  		// ServeFileDownload是相对使用频率比较高的方法,用于直接引导客户端下载指定路径的文件,并可以重新给定下载的文件名称。
    33  		//g.RequestFromCtx(ctx).Response.ServeFileDownload(file.Src, "testDownload.jpg")
    34  
    35  	} else { // oss 访问路径
    36  		g.RequestFromCtx(ctx).Response.RedirectTo(file.Src) // 直接引导客户端下载指定路径的文件
    37  	}
    38  
    39  	//return (*sys_api.UploadFileRes)(&file.SysFile), err
    40  	return nil, err
    41  }