-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathasset_manager.go
62 lines (55 loc) · 1.9 KB
/
asset_manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package media_library
import (
"bytes"
"encoding/json"
"fmt"
"io"
"regexp"
"github.com/jinzhu/gorm"
"github.com/qor/admin"
"github.com/qor/qor/resource"
)
// AssetManager defined a asset manager that could be used to manage assets in qor admin
type AssetManager struct {
gorm.Model
File FileSystem `media_library:"URL:/system/assets/{{primary_key}}/{{filename_with_hash}}"`
}
// ConfigureQorResource configure qor locale for Qor Admin
func (*AssetManager) ConfigureQorResource(res resource.Resourcer) {
if res, ok := res.(*admin.Resource); ok {
router := res.GetAdmin().GetRouter()
router.Post(fmt.Sprintf("/%v/upload", res.ToParam()), func(context *admin.Context) {
result := AssetManager{}
result.File.Scan(context.Request.MultipartForm.File["file"])
context.GetDB().Save(&result)
bytes, _ := json.Marshal(map[string]string{"filelink": result.File.URL(), "filename": result.File.GetFileName()})
context.Writer.Write(bytes)
})
assetURL := regexp.MustCompile(`^/system/assets/(\d+)/`)
router.Post(fmt.Sprintf("/%v/crop", res.ToParam()), func(context *admin.Context) {
defer context.Request.Body.Close()
var (
err error
url struct{ URL string }
buf bytes.Buffer
)
io.Copy(&buf, context.Request.Body)
if err = json.Unmarshal(buf.Bytes(), &url); err == nil {
if matches := assetURL.FindStringSubmatch(url.URL); len(matches) > 1 {
result := &AssetManager{}
if err = context.GetDB().Find(result, matches[1]).Error; err == nil {
if err = result.File.Scan(buf.Bytes()); err == nil {
if err = context.GetDB().Save(result).Error; err == nil {
bytes, _ := json.Marshal(map[string]string{"url": result.File.URL(), "filename": result.File.GetFileName()})
context.Writer.Write(bytes)
return
}
}
}
}
}
bytes, _ := json.Marshal(map[string]string{"err": err.Error()})
context.Writer.Write(bytes)
})
}
}