logfiledown.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /**
  2. * @Author: zou.yingbin
  3. * @Create : 2021/10/15 16:28
  4. * @Modify : 2021/10/15 16:28
  5. */
  6. package other
  7. import (
  8. "fmt"
  9. "github.com/gin-gonic/gin"
  10. "io/ioutil"
  11. "mtp2_if/config"
  12. "net/http"
  13. )
  14. // DownloadFile 提供文件下载功能
  15. func DownloadFile(ctx *gin.Context) {
  16. fileDir := config.SerCfg.LogCfg.LogPath
  17. if len(fileDir) > 0 {
  18. if nLen := len(fileDir); fileDir[nLen-1] != '/' {
  19. fileDir += "/"
  20. }
  21. }
  22. filename := ctx.DefaultQuery("filename", "")
  23. fGetFile := func(filename string) (fullPath string, err error) {
  24. err = nil
  25. if sfile, err := ioutil.ReadDir(fileDir); err == nil {
  26. bExist := false
  27. for _, info := range sfile {
  28. if !info.IsDir() && info.Name() == filename {
  29. fullPath = fileDir + filename
  30. bExist = true
  31. break
  32. }
  33. }
  34. if !bExist {
  35. err = fmt.Errorf("not found:%v", filename)
  36. }
  37. } else {
  38. err = fmt.Errorf("err:%v", err)
  39. }
  40. return
  41. }
  42. if fullPath, err := fGetFile(filename); err == nil && fullPath != "" {
  43. fmt.Println("download file:", fullPath)
  44. ctx.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
  45. ctx.Writer.Header().Add("Content-Type", "application/octet-stream")
  46. ctx.File(fullPath)
  47. } else {
  48. strErr := fmt.Sprintf("/404:%v", err)
  49. fmt.Println(strErr)
  50. ctx.Redirect(http.StatusFound, strErr)
  51. }
  52. }