Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file is a valid image?

Tags:

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?

like image 287
Dmitry Papka Avatar asked Sep 21 '14 12:09

Dmitry Papka


1 Answers

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).

like image 140
Salvador Dali Avatar answered Oct 16 '22 03:10

Salvador Dali