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.

attachment.go 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. ctx.Error(400, ErrFileTypeForbidden.Error())
  50. return
  51. }
  52. attach, err := models.NewAttachment(header.Filename, buf, file)
  53. if err != nil {
  54. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  55. return
  56. }
  57. log.Trace("New attachment uploaded: %s", attach.UUID)
  58. ctx.JSON(200, map[string]string{
  59. "uuid": attach.UUID,
  60. })
  61. }