I'm working on an application in which I need to upload images to an S3 bucket. The images come from HTTP requests inside form datas. I upload the images directly to S3 as objects (https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_object), without saving them on my backend for security purposes. But for other security purposes, is there a way to check if my image object is actually representing an image before uploading it to S3?
Asked
Active
Viewed 449 times
2

John Rotenstein
- 241,921
- 22
- 380
- 470

Mehdi Khlifi
- 405
- 8
- 21
-
If you read the images via HTTP maybe you can look at the content-type HTTP header and see if it point to image? – balderman Sep 30 '20 at 10:43
-
Ignoring AWS and S3, how would you do this normally? What makes a file an "image", without actually trying to parse the file itself? Would you be willing to trust the Content Type? – John Rotenstein Oct 01 '20 at 00:43
-
Content-type has no valuable information whether the file is actually an image or no. @JohnRotenstein That's exactly my question, is there a way to know if a variable represents an image? – Mehdi Khlifi Oct 01 '20 at 09:03
-
[python - How to check if a file is a valid image file? - Stack Overflow](https://stackoverflow.com/questions/889333/how-to-check-if-a-file-is-a-valid-image-file) – John Rotenstein Oct 01 '20 at 10:23
1 Answers
0
Given a bytes object, the following solution worked out for me:
def validate_image(bytes_object):
import io
from PIL import Image
try:
Image.open(io.BytesIO(bytes_array))
except OSError:
print('Not a valid image')

Mehdi Khlifi
- 405
- 8
- 21