download.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "io"
  7. "path"
  8. "github.com/gogits/gogs/modules/base"
  9. "github.com/gogits/gogs/modules/git"
  10. "github.com/gogits/gogs/modules/middleware"
  11. )
  12. func ServeBlob(ctx *middleware.Context, blob *git.Blob) error {
  13. dataRc, err := blob.Data()
  14. if err != nil {
  15. return err
  16. }
  17. buf := make([]byte, 1024)
  18. n, _ := dataRc.Read(buf)
  19. if n > 0 {
  20. buf = buf[:n]
  21. }
  22. _, isTextFile := base.IsTextFile(buf)
  23. if ! isTextFile {
  24. _, isImageFile := base.IsImageFile(buf)
  25. if !isImageFile {
  26. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+path.Base(ctx.Repo.TreeName))
  27. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  28. }
  29. }
  30. ctx.Resp.Write(buf)
  31. _, err = io.Copy(ctx.Resp, dataRc)
  32. return err
  33. }
  34. func SingleDownload(ctx *middleware.Context) {
  35. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName)
  36. if err != nil {
  37. if err == git.ErrNotExist {
  38. ctx.Handle(404, "GetBlobByPath", nil)
  39. } else {
  40. ctx.Handle(500, "GetBlobByPath", err)
  41. }
  42. return
  43. }
  44. if err = ServeBlob(ctx, blob); err != nil {
  45. ctx.Handle(500, "ServeBlob", err)
  46. }
  47. }