How to check if a file is a valid image?

Dmitry Papka picture Dmitry Papka · Sep 21, 2014 · Viewed 13.2k times · Source

I am building a web application.

On one of the pages there is an upload form, where user can upload a file. After the upload is done, I want to check on the server if the uploaded file is an image.

Is it possible to check this beyond simple file extension checking (i.e. not assuming that a *.png filename is actually a PNG image)?

For example, if I edit a JPEG image adding/editing a byte in a random place to make an invalid JPEG file, I want to detect that it is not a JPEG image anymore. I used to do such type of thing via PHP some time ago, using a GD library.

I would like to know if it is possible to do with Go?

Answer

Salvador Dali picture Salvador Dali · Jul 4, 2016

DetectContentType is way better than a manual magic number checking. The use is simple:

clientFile, _, _ := r.FormFile("img") // or get your file from a file system
defer clientFile.Close()
buff := make([]byte, 512) // docs tell that it take only first 512 bytes into consideration
if _, err = clientFile.Read(buff); err != nil {
     fmt.Println(err) // do something with that error
     return
}

fmt.Println(http.DetectContentType(buff)) // do something based on your detection.

Using this method you need to know that you still are not guaranteed to have a correct file. So I would recommend to do some image manipulation with that file (like resize it to make sure this is really an image).