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))
fileExtension := filepath.Ext(header.Filename)
if len(fileExtension) == 0 {
// Find correct file extension if original filename does not contain one
mimeType := header.Header.Get("content-type") mimeType := header.Header.Get("content-type")
originalName := header.Filename if len(mimeType) > 0 {
if strings.Contains(mimeType, "jpeg") || strings.Contains(originalName, ".jpeg") || strings.Contains(originalName, ".jpg") { allExtensions, _ := mime.ExtensionsByType(mimeType)
fileName += ".jpg" if len(allExtensions) > 0 {
} else if strings.Contains(mimeType, "png") || strings.Contains(originalName, ".png") { fileExtension = allExtensions[0]
fileName += ".png"
} }
}
}
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)