| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- /**
- * @Author: zou.yingbin
- * @Create : 2021/10/15 16:28
- * @Modify : 2021/10/15 16:28
- */
- package other
- import (
- "fmt"
- "github.com/gin-gonic/gin"
- "io/ioutil"
- "mtp2_if/config"
- "net/http"
- )
- // DownloadFile 提供文件下载功能
- func DownloadFile(ctx *gin.Context) {
- fileDir := config.SerCfg.LogCfg.LogPath
- if len(fileDir) > 0 {
- if nLen := len(fileDir); fileDir[nLen-1] != '/' {
- fileDir += "/"
- }
- }
- filename := ctx.DefaultQuery("filename", "")
- fGetFile := func(filename string) (fullPath string, err error) {
- err = nil
- if sfile, err := ioutil.ReadDir(fileDir); err == nil {
- bExist := false
- for _, info := range sfile {
- if !info.IsDir() && info.Name() == filename {
- fullPath = fileDir + filename
- bExist = true
- break
- }
- }
- if !bExist {
- err = fmt.Errorf("not found:%v", filename)
- }
- } else {
- err = fmt.Errorf("err:%v", err)
- }
- return
- }
- if fullPath, err := fGetFile(filename); err == nil && fullPath != "" {
- fmt.Println("download file:", fullPath)
- ctx.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
- ctx.Writer.Header().Add("Content-Type", "application/octet-stream")
- ctx.File(fullPath)
- } else {
- strErr := fmt.Sprintf("/404:%v", err)
- fmt.Println(strErr)
- ctx.Redirect(http.StatusFound, strErr)
- }
- }
|