Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a file as image on the server before uploading to S3?

The flow is:

  • The user selects an image on the client.
  • Only filename, content-type and size are sent to the server. (E.g. "file.png", "image/png", "123123")
  • The response are fields and policies for upload directly to S3. (E.g. "key: xxx, "alc": ...)

The case is that if I change the extension of "file.pdf" to "file.png" and then uploads it, the data sent to the server before uploads to S3 are:

  • "file.png"
  • "image/png"

The servers says "ok" and return the S3 fields for upload .

But the content type sent is not a real content type. But how I can validate this on the server?

Thanks!


Example:

Testing Redactorjs server side code (https://github.com/dybskiy/redactor-js/blob/master/demo/scripts/image_upload.php) it checks the file content type. But trying upload fake image (test here: http://imperavi.com/redactor/), it not allows the fake image. Like I want!

But how it's possible? Look at the request params: (It sends as image/jpeg, that should be valid)

enter image description here

like image 552
Luccas Avatar asked Sep 03 '25 09:09

Luccas


1 Answers

When I was dealing with this question at work I found a solution using Mechanize.

Say you have an image url, url = "http://my.image.com"

Then you can use img = Mechanize.new.get(url)[:body]

The way to test whether img is really an image is by issuing the following test:

img.is_a?(Mechanize::Image)

If the image is not legitimate, this will return false.

There may be a way to load the image from file instead of URL, I am not sure, but I recommend looking at the mechanize docs to check.

like image 157
max pleaner Avatar answered Sep 04 '25 22:09

max pleaner