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.

73 lines
1.8 KiB

  1. // Copyright 2017 The Gitea 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. "net/http"
  8. "strings"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/context"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. )
  14. func renderAttachmentSettings(ctx *context.Context) {
  15. ctx.Data["RequireDropzone"] = true
  16. ctx.Data["IsAttachmentEnabled"] = setting.AttachmentEnabled
  17. ctx.Data["AttachmentAllowedTypes"] = setting.AttachmentAllowedTypes
  18. ctx.Data["AttachmentMaxSize"] = setting.AttachmentMaxSize
  19. ctx.Data["AttachmentMaxFiles"] = setting.AttachmentMaxFiles
  20. }
  21. // UploadAttachment response for uploading issue's attachment
  22. func UploadAttachment(ctx *context.Context) {
  23. if !setting.AttachmentEnabled {
  24. ctx.Error(404, "attachment is not enabled")
  25. return
  26. }
  27. file, header, err := ctx.Req.FormFile("file")
  28. if err != nil {
  29. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  30. return
  31. }
  32. defer file.Close()
  33. buf := make([]byte, 1024)
  34. n, _ := file.Read(buf)
  35. if n > 0 {
  36. buf = buf[:n]
  37. }
  38. fileType := http.DetectContentType(buf)
  39. allowedTypes := strings.Split(setting.AttachmentAllowedTypes, ",")
  40. allowed := false
  41. for _, t := range allowedTypes {
  42. t := strings.Trim(t, " ")
  43. if t == "*/*" || t == fileType {
  44. allowed = true
  45. break
  46. }
  47. }
  48. if !allowed {
  49. log.Info("Attachment with type %s blocked from upload", fileType)
  50. ctx.Error(400, ErrFileTypeForbidden.Error())
  51. return
  52. }
  53. attach, err := models.NewAttachment(header.Filename, buf, file)
  54. if err != nil {
  55. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  56. return
  57. }
  58. log.Trace("New attachment uploaded: %s", attach.UUID)
  59. ctx.JSON(200, map[string]string{
  60. "uuid": attach.UUID,
  61. })
  62. }