Skip to content

Commit

Permalink
Merge pull request #31 from Dan6erbond:develop
Browse files Browse the repository at this point in the history
feat: Detect MIME Type from File Uploads
  • Loading branch information
Dan6erbond authored May 20, 2023
2 parents 1c414b2 + ddefe1b commit f798d9c
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions server/pkg/apis/files.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package apis

import (
"mime"
"mime/multipart"
"net/http"
"path/filepath"

"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/apis"
Expand All @@ -12,9 +14,28 @@ import (
"github.com/pocketbase/pocketbase/tools/filesystem"
)

const ApplicationOctetStream = "application/octet-stream"

func newFile(app core.App, files *models.Collection, author *models.Record, file *multipart.FileHeader) (*models.Record, error) {
f, err := filesystem.NewFileFromMultipart(file)

var contentType string

if ct := file.Header.Get("Content-Type"); ct != "" {
contentType = ct
}

// Guess content-type from extension if missing
if contentType == "" || contentType == ApplicationOctetStream {
if ext := filepath.Ext(file.Filename); ext != "" {
contentType = mime.TypeByExtension(ext)
}
}

if contentType == "" {
contentType = ApplicationOctetStream
}

if err != nil {
return nil, apis.NewApiError(http.StatusInternalServerError, "", err)
}
Expand All @@ -27,6 +48,7 @@ func newFile(app core.App, files *models.Collection, author *models.Record, file
"author": author.Id,
"tags": "[]",
"tagsSuggestions": "[]",
"type": contentType,
})
form.AddFiles("file", f)

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

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

if ff != nil && err != nil {
if ff != nil && err == nil {
file, err := newFile(e.App, files, record, ff)

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

if !ok {
return apis.NewApiError(http.StatusBadRequest, "Either the file or files form body must be set.", nil)
return apis.NewApiError(http.StatusBadRequest, "Either the file or files form fields must be set.", nil)
}

for _, f := range formFiles {
Expand Down

0 comments on commit f798d9c

Please sign in to comment.