You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.3 KiB

10 years ago
10 years ago
10 years ago
10 years ago
  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. contentType, isTextFile := base.IsTextFile(buf)
  23. _, isImageFile := base.IsImageFile(buf)
  24. ctx.Resp.Header().Set("Content-Type", contentType)
  25. if !isTextFile && !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. ctx.Resp.Write(buf)
  30. io.Copy(ctx.Resp, dataRc)
  31. return nil
  32. }
  33. func SingleDownload(ctx *middleware.Context) {
  34. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName)
  35. if err != nil {
  36. if err == git.ErrNotExist {
  37. ctx.Handle(404, "GetBlobByPath", nil)
  38. } else {
  39. ctx.Handle(500, "GetBlobByPath", err)
  40. }
  41. return
  42. }
  43. if err = ServeBlob(ctx, blob); err != nil {
  44. ctx.Handle(500, "ServeBlob", err)
  45. }
  46. }