Last active
May 16, 2022 05:53
-
-
Save philippta/4518f47e4e74fa415b79c6ced553d80c to your computer and use it in GitHub Desktop.
Detect uploaded file type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func uploadImage(w http.ResponseWriter, r *http.Request) { | |
// Create buffer to read magic number of uploaded file | |
magicNumber := make([]byte, 3) | |
// Read first 3 bytes of uploaded file | |
_, err := r.Body.Read(magicNumber) | |
// handle err | |
// Check magic number against png, jpg, gif | |
// https://en.wikipedia.org/wiki/List_of_file_signatures | |
ext := "" | |
switch { | |
case bytes.Compare(magicNumber, []byte{0xFF, 0xD8, 0xFF}) == 0: // ÿØÿ (JPG) | |
log.Println("file is a jpg") | |
ext = ".jpg" | |
case bytes.Compare(magicNumber, []byte{0x89, 0x50, 0x4E}) == 0: // .PNG (PNG) | |
log.Println("file is a png") | |
ext = ".png" | |
case bytes.Compare(magicNumber, []byte{0x47, 0x49, 0x46}) == 0: // GIF (GIF) | |
log.Println("file is a gif") | |
ext = ".gif" | |
default: | |
log.Println("file is neither") | |
http.Error(w, "invalid file", http.StatusBadRequest) | |
return | |
} | |
// Stitch the bytes back together | |
fileReader := io.MultiReader(bytes.NewReader(magicNumber), r.Body) | |
// Create new file for storage | |
out, err := os.Create("thefile" + ext) | |
// handle err | |
// Save file to disk | |
io.Copy(out, fileReader) | |
// Or in your case, respond back to client | |
io.Copy(w, fileReader) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment