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.

62 lines
1.5 KiB

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. "code.gitea.io/git"
  9. "code.gitea.io/gitea/modules/base"
  10. "code.gitea.io/gitea/modules/context"
  11. )
  12. // ServeData download file from io.Reader
  13. func ServeData(ctx *context.Context, name string, reader io.Reader) error {
  14. buf := make([]byte, 1024)
  15. n, _ := reader.Read(buf)
  16. if n > 0 {
  17. buf = buf[:n]
  18. }
  19. if !base.IsTextFile(buf) {
  20. if !base.IsImageFile(buf) {
  21. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename=\""+path.Base(ctx.Repo.TreePath)+"\"")
  22. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  23. }
  24. } else if !ctx.QueryBool("render") {
  25. ctx.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
  26. }
  27. ctx.Resp.Write(buf)
  28. _, err := io.Copy(ctx.Resp, reader)
  29. return err
  30. }
  31. // ServeBlob download a git.Blob
  32. func ServeBlob(ctx *context.Context, blob *git.Blob) error {
  33. dataRc, err := blob.Data()
  34. if err != nil {
  35. return err
  36. }
  37. return ServeData(ctx, ctx.Repo.TreePath, dataRc)
  38. }
  39. // SingleDownload download a file by repos path
  40. func SingleDownload(ctx *context.Context) {
  41. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath)
  42. if err != nil {
  43. if git.IsErrNotExist(err) {
  44. ctx.Handle(404, "GetBlobByPath", nil)
  45. } else {
  46. ctx.Handle(500, "GetBlobByPath", err)
  47. }
  48. return
  49. }
  50. if err = ServeBlob(ctx, blob); err != nil {
  51. ctx.Handle(500, "ServeBlob", err)
  52. }
  53. }