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.

71 lines
1.8 KiB

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