download.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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/middleware"
  10. )
  11. func SingleDownload(ctx *middleware.Context) {
  12. blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName)
  13. if err != nil {
  14. ctx.Handle(500, "GetBlobByPath", err)
  15. return
  16. }
  17. dataRc, err := blob.Data()
  18. if err != nil {
  19. ctx.Handle(500, "Data", err)
  20. return
  21. }
  22. buf := make([]byte, 1024)
  23. n, _ := dataRc.Read(buf)
  24. if n > 0 {
  25. buf = buf[:n]
  26. }
  27. contentType, isTextFile := base.IsTextFile(buf)
  28. _, isImageFile := base.IsImageFile(buf)
  29. ctx.Resp.Header().Set("Content-Type", contentType)
  30. if !isTextFile && !isImageFile {
  31. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+path.Base(ctx.Repo.TreeName))
  32. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  33. }
  34. ctx.Resp.Write(buf)
  35. io.Copy(ctx.Resp, dataRc)
  36. }