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.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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(&models.Attachment{
  54. UploaderID: ctx.User.ID,
  55. Name: header.Filename,
  56. }, buf, file)
  57. if err != nil {
  58. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  59. return
  60. }
  61. log.Trace("New attachment uploaded: %s", attach.UUID)
  62. ctx.JSON(200, map[string]string{
  63. "uuid": attach.UUID,
  64. })
  65. }