Skip to content

Commit

Permalink
feat(server): ✨ detect MIME type from file headers
Browse files Browse the repository at this point in the history
  • Loading branch information
Dan6erbond committed May 20, 2023
1 parent a71ec2e commit e5c94e0
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 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

0 comments on commit e5c94e0

Please sign in to comment.