File Upload
By default, GoAdmin provides a local file upload engine that supports uploading files to the server. Use the directory that needs to be set up in the global configuration and the prefix for uploading file access.
1
package config
2
3
// Storage directory: store avatar and other uploaded files
4
type Store struct {
5
Path string // relative or absolute path, the file will be stored here
6
Prefix string // access url prefix
7
}
8
9
type Config struct {
10
11
...
12
13
// Upload file storage location
14
Store Store `json:"store"`
15
16
// File upload engine
17
FileUploadEngine FileUploadEngine `json:"file_upload_engine"`
18
19
...
20
}
21
22
type FileUploadEngine struct {
23
Name string
24
Config map[string]interface{}
25
}
Copied!
If you want to customize the upload location, such as uploading to cloud, aws cloud and other cloud platforms, then you need to write an upload engine yourself. Here's how to write your own engine:

Type of engine

1
package file
2
3
type Uploader interface {
4
Upload(*multipart.Form) error
5
}
6
7
type UploaderGenerator func() Uploader
8
9
func AddUploader(name string, up UploaderGenerator) {
10
...
11
}
Copied!

How to

We need to call the AddUploader method to add an upload engine. The first parameter is the name of the engine (which will be used in the global configuration) and the second parameter is the engine generation function.
Suppose we want to add a aws cloud upload engine, then it can be similar like this:
1
package main
2
3
import (
4
...
5
"github.com/GoAdminGroup/go-admin/modules/file"
6
...
7
)
8
9
type AwsUploader struct {
10
Bucket string
11
Region string
12
SecretId string
13
SecretKey string
14
15
Prefix string
16
Path string
17
}
18
19
func (q AwsUploader) Upload(*multipart.Form) error {
20
// Receive a form type, for upload logic here
21
// This invocation framework auxiliary function
22
file.Upload(func(*multipart.FileHeader, string) (string, error){
23
// Here for upload logic, return to the file path and error information
24
}, form)
25
}
26
27
func main() {
28
29
...
30
31
file.AddUploader("aws", func() file.Uploader {
32
return &AwsUploader{
33
Bucket: config.Get().FileUploadEngine.Config["bucket"].(string),
34
Region: config.Get().FileUploadEngine.Config["region"].(string),
35
SecretId: config.Get().FileUploadEngine.Config["secret_id"].(string),
36
SecretKey: config.Get().FileUploadEngine.Config["secret_key"].(string),
37
Prefix: config.Get().FileUploadEngine.Config["prefix"].(string),
38
Path: config.Get().FileUploadEngine.Config["path"].(string),
39
}
40
})
41
42
cfg := config.Config{
43
...
44
45
FileUploadEngine: config.FileUploadEngine{
46
Name: "aws",
47
Config: map[string]interface{}{
48
"bucket": "xxx",
49
"region": "xxx",
50
"secret_id": "xxx",
51
"secret_key": "xxx",
52
"prefix": "xxx",
53
"path": "xxx",
54
},
55
}
56
57
...
58
}
59
60
...
61
}
Copied!
Finish a aws cloud upload file engine!🍺🍺
Last modified 1yr ago
Copy link