upload.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package media
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "gorm.io/gorm"
  6. "gorm.io/gorm/schema"
  7. )
  8. var (
  9. // set MediaLibraryURL to change the default url /system/{{class}}/{{primary_key}}/{{column}}.{{extension}}
  10. MediaLibraryURL = ""
  11. )
  12. func cropField(field *schema.Field, db *gorm.DB) (cropped bool, err error) {
  13. if !field.ReflectValueOf(db.Statement.Context, db.Statement.ReflectValue).CanAddr() {
  14. return
  15. }
  16. media, ok := field.ReflectValueOf(db.Statement.Context, db.Statement.ReflectValue).Addr().Interface().(Media)
  17. if !ok {
  18. return
  19. }
  20. if media.Cropped() {
  21. return
  22. }
  23. option := parseTagOption(field.Tag.Get("mediaLibrary"))
  24. if MediaLibraryURL != "" {
  25. option.Set("url", MediaLibraryURL)
  26. }
  27. if media.GetFileHeader() == nil && !media.NeedCrop() {
  28. return
  29. }
  30. var mediaFile FileInterface
  31. if fileHeader := media.GetFileHeader(); fileHeader != nil {
  32. mediaFile, err = media.GetFileHeader().Open()
  33. } else {
  34. mediaFile, err = media.Retrieve(media.URL("original"))
  35. }
  36. if err != nil {
  37. return false, err
  38. }
  39. // TODO: this is a defensive condition. probably not needed anymore
  40. if mediaFile == nil {
  41. return false, errors.New("can't find mediaFile")
  42. }
  43. defer mediaFile.Close()
  44. media.Cropped(true)
  45. if url := media.GetURL(option, db, field, media); url == "" {
  46. return false, errors.New("invalid URL")
  47. } else {
  48. result, _ := json.Marshal(map[string]string{"Url": url})
  49. media.Scan(string(result))
  50. }
  51. var handled = false
  52. for _, handler := range mediaHandlers {
  53. if !handler.CouldHandle(media) {
  54. continue
  55. }
  56. mediaFile.Seek(0, 0)
  57. if handler.Handle(media, mediaFile, option) == nil {
  58. handled = true
  59. }
  60. }
  61. // Save File
  62. if !handled {
  63. err = media.Store(media.URL(), option, mediaFile)
  64. return true, err
  65. }
  66. return true, nil
  67. }
  68. func SaveUploadAndCropImage(db *gorm.DB, obj interface{}) (err error) {
  69. db = db.Model(obj).Save(obj)
  70. err = db.Error
  71. if err != nil {
  72. return
  73. }
  74. var updateColumns = map[string]interface{}{}
  75. for _, field := range db.Statement.Schema.Fields {
  76. ok, err := cropField(field, db)
  77. if err != nil {
  78. return err
  79. }
  80. if ok {
  81. updateColumns[field.DBName] = field.ReflectValueOf(db.Statement.Context, db.Statement.ReflectValue).Addr().Interface()
  82. }
  83. }
  84. if len(updateColumns) == 0 {
  85. return
  86. }
  87. err = db.UpdateColumns(updateColumns).Error
  88. return
  89. }