Use hash as file name to de-duplicate uploads

kcoram/uplift
Jan-Lukas Else 2020-01-01 15:43:59 +01:00
parent 222afd3957
commit 1556bd5128
1 changed files with 12 additions and 2 deletions

View File

@ -1,9 +1,11 @@
package main
import (
"crypto/sha256"
"fmt"
"io"
"net/http"
"strings"
"time"
)
func HandleMedia(w http.ResponseWriter, r *http.Request) {
@ -34,7 +36,15 @@ func HandleMedia(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Failed to get file"))
return
}
fileName := generateRandomString(time.Now(), 15)
hashFile, _, _ := r.FormFile("file")
h := sha256.New()
defer func() { _ = hashFile.Close() }()
if _, err := io.Copy(h, hashFile); err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("Failed to calculate hash of file"))
return
}
fileName := fmt.Sprintf("%x", h.Sum(nil))
mimeType := header.Header.Get("content-type")
originalName := header.Filename
if strings.Contains(mimeType, "jpeg") || strings.Contains(originalName, ".jpeg") || strings.Contains(originalName, ".jpg") {