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.

68 lines
1.7 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. "fmt"
  7. "io"
  8. "strings"
  9. "code.gitea.io/git"
  10. "code.gitea.io/gitea/modules/base"
  11. "code.gitea.io/gitea/modules/context"
  12. )
  13. // ServeData download file from io.Reader
  14. func ServeData(ctx *context.Context, name string, reader io.Reader) error {
  15. buf := make([]byte, 1024)
  16. n, _ := reader.Read(buf)
  17. if n > 0 {
  18. buf = buf[:n]
  19. }
  20. ctx.Resp.Header().Set("Cache-Control", "public,max-age=86400")
  21. // Google Chrome dislike commas in filenames, so let's change it to a space
  22. name = strings.Replace(name, ",", " ", -1)
  23. if base.IsTextFile(buf) || ctx.QueryBool("render") {
  24. ctx.Resp.Header().Set("Content-Type", "text/plain; charset=utf-8")
  25. } else if base.IsImageFile(buf) || base.IsPDFFile(buf) {
  26. ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename="%s"`, name))
  27. } else {
  28. ctx.Resp.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, name))
  29. }
  30. ctx.Resp.Write(buf)
  31. _, err := io.Copy(ctx.Resp, reader)
  32. return err
  33. }
  34. // ServeBlob download a git.Blob
  35. func ServeBlob(ctx *context.Context, blob *git.Blob) error {
  36. dataRc, err := blob.Data()
  37. if err != nil {
  38. return err
  39. }
  40. return ServeData(ctx, ctx.Repo.TreePath, dataRc)
  41. }
  42. // SingleDownload download a file by repos path
  43. func SingleDownload(ctx *context.Context) {
  44. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreePath)
  45. if err != nil {
  46. if git.IsErrNotExist(err) {
  47. ctx.Handle(404, "GetBlobByPath", nil)
  48. } else {
  49. ctx.Handle(500, "GetBlobByPath", err)
  50. }
  51. return
  52. }
  53. if err = ServeBlob(ctx, blob); err != nil {
  54. ctx.Handle(500, "ServeBlob", err)
  55. }
  56. }