1
1
package apis
2
2
3
3
import (
4
+ "mime"
4
5
"mime/multipart"
5
6
"net/http"
7
+ "path/filepath"
6
8
7
9
"github.com/labstack/echo/v5"
8
10
"github.com/pocketbase/pocketbase/apis"
@@ -12,9 +14,28 @@ import (
12
14
"github.com/pocketbase/pocketbase/tools/filesystem"
13
15
)
14
16
17
+ const ApplicationOctetStream = "application/octet-stream"
18
+
15
19
func newFile (app core.App , files * models.Collection , author * models.Record , file * multipart.FileHeader ) (* models.Record , error ) {
16
20
f , err := filesystem .NewFileFromMultipart (file )
17
21
22
+ var contentType string
23
+
24
+ if ct := file .Header .Get ("Content-Type" ); ct != "" {
25
+ contentType = ct
26
+ }
27
+
28
+ // Guess content-type from extension if missing
29
+ if contentType == "" || contentType == ApplicationOctetStream {
30
+ if ext := filepath .Ext (file .Filename ); ext != "" {
31
+ contentType = mime .TypeByExtension (ext )
32
+ }
33
+ }
34
+
35
+ if contentType == "" {
36
+ contentType = ApplicationOctetStream
37
+ }
38
+
18
39
if err != nil {
19
40
return nil , apis .NewApiError (http .StatusInternalServerError , "" , err )
20
41
}
@@ -27,6 +48,7 @@ func newFile(app core.App, files *models.Collection, author *models.Record, file
27
48
"author" : author .Id ,
28
49
"tags" : "[]" ,
29
50
"tagsSuggestions" : "[]" ,
51
+ "type" : contentType ,
30
52
})
31
53
form .AddFiles ("file" , f )
32
54
@@ -60,7 +82,7 @@ func RegisterFileRoutes(e *core.ServeEvent) error {
60
82
61
83
ff , err := c .FormFile ("file" )
62
84
63
- if ff != nil && err ! = nil {
85
+ if ff != nil && err = = nil {
64
86
file , err := newFile (e .App , files , record , ff )
65
87
66
88
if err != nil {
@@ -77,7 +99,7 @@ func RegisterFileRoutes(e *core.ServeEvent) error {
77
99
formFiles , ok := form .File ["files" ]
78
100
79
101
if ! ok {
80
- return apis .NewApiError (http .StatusBadRequest , "Either the file or files form body must be set." , nil )
102
+ return apis .NewApiError (http .StatusBadRequest , "Either the file or files form fields must be set." , nil )
81
103
}
82
104
83
105
for _ , f := range formFiles {
0 commit comments