Improve extension handling for uploaded files

kcoram/uplift
Jan-Lukas Else 2020-01-01 16:03:13 +01:00
parent 1556bd5128
commit 5ecada8f54
1 changed files with 13 additions and 6 deletions

View File

@ -4,7 +4,9 @@ import (
"crypto/sha256" "crypto/sha256"
"fmt" "fmt"
"io" "io"
"mime"
"net/http" "net/http"
"path/filepath"
"strings" "strings"
) )
@ -45,13 +47,18 @@ func HandleMedia(w http.ResponseWriter, r *http.Request) {
return return
} }
fileName := fmt.Sprintf("%x", h.Sum(nil)) fileName := fmt.Sprintf("%x", h.Sum(nil))
mimeType := header.Header.Get("content-type") fileExtension := filepath.Ext(header.Filename)
originalName := header.Filename if len(fileExtension) == 0 {
if strings.Contains(mimeType, "jpeg") || strings.Contains(originalName, ".jpeg") || strings.Contains(originalName, ".jpg") { // Find correct file extension if original filename does not contain one
fileName += ".jpg" mimeType := header.Header.Get("content-type")
} else if strings.Contains(mimeType, "png") || strings.Contains(originalName, ".png") { if len(mimeType) > 0 {
fileName += ".png" allExtensions, _ := mime.ExtensionsByType(mimeType)
if len(allExtensions) > 0 {
fileExtension = allExtensions[0]
}
}
} }
fileName += fileExtension
location, err := SelectedMediaStorage.Upload(fileName, file) location, err := SelectedMediaStorage.Upload(fileName, file)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)