Golang : How to verify uploaded file is image or allowed file types
Problem :
How do I verify if an uploaded file to my server is ... let say I only allow images(JPG, PNG, GIF)... is indeed image file.
Solution :
Use DetectContentType function to detect the uploaded file. Only proceed further if the uploaded file is image or allowed file types.
If not, abort and prompt error message.
The code will assume that the target file is uploaded from client. To see how to upload file in Golang, please visit https://www.socketloop.com/tutorials/golang-upload-file
Codes :
package main
import (
"fmt"
"net/http"
"os"
"runtime"
)
func main() {
// maximize CPU usage for maximum performance
runtime.GOMAXPROCS(runtime.NumCPU())
// open the uploaded file
file, err := os.Open("./img.png")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
buff := make([]byte, 512) // why 512 bytes ? see http://golang.org/pkg/net/http/#DetectContentType
_, err = file.Read(buff)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
filetype := http.DetectContentType(buff)
fmt.Println(filetype)
switch filetype {
case "image/jpeg", "image/jpg":
fmt.Println(filetype)
case "image/gif":
fmt.Println(filetype)
case "image/png":
fmt.Println(filetype)
case "application/pdf": // not image, but application !
fmt.Println(filetype)
default:
fmt.Println("unknown file type uploaded")
}
}
See also : Golang : Upload file from web browser to server
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.2k Golang : Scan forex opportunities by Bollinger bands
+21.8k Golang : Encrypt and decrypt data with TripleDES
+11.6k CodeIgniter : Import Linkedin data
+10.3k Golang : How to profile or log time spend on execution?
+11.3k Golang : Fix - does not implement sort.Interface (missing Len method)
+7.2k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+6.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+6.5k Golang : Handling image beyond OpenCV video capture boundary
+22.1k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+7.4k Golang : Not able to grep log.Println() output
+5.6k Golang : Stop goroutine without channel
+17.2k Golang : Fix cannot convert buffer (type *bytes.Buffer) to type string error