system_file_download_logic.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package system
  2. import (
  3. "context"
  4. "git.i2edu.net/i2/i2-bill-api/model"
  5. "io"
  6. "net/http"
  7. "strconv"
  8. "git.i2edu.net/i2/i2-bill-api/internal/svc"
  9. "git.i2edu.net/i2/i2-bill-api/internal/types"
  10. "git.i2edu.net/i2/go-zero/core/logx"
  11. )
  12. type SystemFileDownloadLogic struct {
  13. logx.Logger
  14. ctx context.Context
  15. svcCtx *svc.ServiceContext
  16. }
  17. func NewSystemFileDownloadLogic(ctx context.Context, svcCtx *svc.ServiceContext) SystemFileDownloadLogic {
  18. return SystemFileDownloadLogic{
  19. Logger: logx.WithContext(ctx),
  20. ctx: ctx,
  21. svcCtx: svcCtx,
  22. }
  23. }
  24. func (l *SystemFileDownloadLogic) SystemFileDownload(w http.ResponseWriter, r *http.Request) (*types.Response, error) {
  25. // todo: add your logic here and delete this line
  26. r.ParseForm()
  27. id := r.FormValue("id")
  28. attachment := new(model.I2billSysAttachment)
  29. _, err := l.svcCtx.DB.ID(id).Get(attachment)
  30. if err != nil {
  31. logx.Error(err.Error())
  32. return &types.Response{500, err.Error(), nil}, nil
  33. }
  34. if attachment.Id == "" {
  35. return &types.Response{200, "", nil}, nil
  36. }
  37. oss, err := svc.GetAliYunOssInstance()
  38. if err != nil {
  39. logx.Error(err.Error())
  40. return &types.Response{500, err.Error(), nil}, nil
  41. }
  42. f, err := oss.Download(attachment)
  43. if err != nil {
  44. logx.Error(err.Error())
  45. return &types.Response{500, err.Error(), nil}, nil
  46. }
  47. w.Header().Set("Content-Disposition", "attachment;filename=\""+attachment.Name+"\"")
  48. w.Header().Set("Content-Type", "application/octet-stream")
  49. w.Header().Set("Content-Length", strconv.FormatInt(int64(attachment.Size), 10))
  50. w.WriteHeader(200)
  51. io.Copy(w, f)
  52. return nil, nil
  53. }