[#289] Add detect mimetype by extension

Signed-off-by: Denis Kirillov <denis@nspcc.ru>
This commit is contained in:
Denis Kirillov 2022-06-29 13:51:05 +03:00 committed by Alex Vanin
parent ef4550ba45
commit 9f740b9683
2 changed files with 31 additions and 14 deletions

View file

@ -69,6 +69,7 @@ func (h *handler) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
}
if len(info.ContentType) == 0 {
if info.ContentType = layer.MimeByFileName(info.Name); len(info.ContentType) == 0 {
buffer := bytes.NewBuffer(make([]byte, 0, sizeToDetectType))
getParams := &layer.GetObjectParams{
ObjectInfo: info,
@ -82,6 +83,7 @@ func (h *handler) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
}
info.ContentType = http.DetectContentType(buffer.Bytes())
}
}
if err = h.setLockingHeaders(r.Context(), bktInfo, info, w.Header()); err != nil {
h.logAndSendError(w, "could not get locking info", reqInfo, err)

View file

@ -7,6 +7,8 @@ import (
"errors"
"fmt"
"io"
"mime"
"path/filepath"
"sort"
"strings"
"time"
@ -155,6 +157,15 @@ func (n *layer) objectGet(ctx context.Context, bktInfo *data.BucketInfo, objID o
return res.Head, nil
}
// MimeByFileName detect mime type by filename extension.
func MimeByFileName(name string) string {
ext := filepath.Ext(name)
if len(ext) == 0 {
return ""
}
return mime.TypeByExtension(ext)
}
// PutObject stores object into NeoFS, took payload from io.Reader.
func (n *layer) PutObject(ctx context.Context, p *PutObjectParams) (*data.ObjectInfo, error) {
own := n.Owner(ctx)
@ -169,11 +180,15 @@ func (n *layer) PutObject(ctx context.Context, p *PutObjectParams) (*data.Object
r := p.Reader
if r != nil {
if len(p.Header[api.ContentType]) == 0 {
if contentType := MimeByFileName(p.Object); len(contentType) == 0 {
d := newDetector(r)
if contentType, err := d.Detect(); err == nil {
if contentType, err = d.Detect(); err == nil {
p.Header[api.ContentType] = contentType
}
r = d.MultiReader()
} else {
p.Header[api.ContentType] = contentType
}
}
}