Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

attachment.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. strings.HasPrefix(fileType, t+";") {
  45. allowed = true
  46. break
  47. }
  48. }
  49. if !allowed {
  50. log.Info("Attachment with type %s blocked from upload", fileType)
  51. ctx.Error(400, ErrFileTypeForbidden.Error())
  52. return
  53. }
  54. attach, err := models.NewAttachment(&models.Attachment{
  55. UploaderID: ctx.User.ID,
  56. Name: header.Filename,
  57. }, buf, file)
  58. if err != nil {
  59. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  60. return
  61. }
  62. log.Trace("New attachment uploaded: %s", attach.UUID)
  63. ctx.JSON(200, map[string]string{
  64. "uuid": attach.UUID,
  65. })
  66. }