Skip to content

Commit f798d9c

Browse files
authored
Merge pull request #31 from Dan6erbond:develop
feat: Detect MIME Type from File Uploads
2 parents 1c414b2 + ddefe1b commit f798d9c

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

server/pkg/apis/files.go

+24-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
package apis
22

33
import (
4+
"mime"
45
"mime/multipart"
56
"net/http"
7+
"path/filepath"
68

79
"github.com/labstack/echo/v5"
810
"github.com/pocketbase/pocketbase/apis"
@@ -12,9 +14,28 @@ import (
1214
"github.com/pocketbase/pocketbase/tools/filesystem"
1315
)
1416

17+
const ApplicationOctetStream = "application/octet-stream"
18+
1519
func newFile(app core.App, files *models.Collection, author *models.Record, file *multipart.FileHeader) (*models.Record, error) {
1620
f, err := filesystem.NewFileFromMultipart(file)
1721

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+
1839
if err != nil {
1940
return nil, apis.NewApiError(http.StatusInternalServerError, "", err)
2041
}
@@ -27,6 +48,7 @@ func newFile(app core.App, files *models.Collection, author *models.Record, file
2748
"author": author.Id,
2849
"tags": "[]",
2950
"tagsSuggestions": "[]",
51+
"type": contentType,
3052
})
3153
form.AddFiles("file", f)
3254

@@ -60,7 +82,7 @@ func RegisterFileRoutes(e *core.ServeEvent) error {
6082

6183
ff, err := c.FormFile("file")
6284

63-
if ff != nil && err != nil {
85+
if ff != nil && err == nil {
6486
file, err := newFile(e.App, files, record, ff)
6587

6688
if err != nil {
@@ -77,7 +99,7 @@ func RegisterFileRoutes(e *core.ServeEvent) error {
7799
formFiles, ok := form.File["files"]
78100

79101
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)
81103
}
82104

83105
for _, f := range formFiles {

0 commit comments

Comments
 (0)