Home > Mobile >  Restrict Upload of Any Image Other Than a Specific One in Flask or Bottle
Restrict Upload of Any Image Other Than a Specific One in Flask or Bottle

Time:04-29

It seems that every question related to this one is asking about restricting uploads by file size, etc.

I am creating an online demo of an application using Bottle (similar to Flask). Part of the program requires a user to download a very specific image and then upload it to see the result of a crop operation done on that image. The image is very particular, so I am trying to save the user time in using the demo, but also prevent shifty image files from being uploaded to the server.

My question is, is it possible to restrict the upload to only that particular image. Is there a way to know that an image uploaded is not that exact image?

For stub testing, I just did the following:

myimg = request.files.get("myimg")
fname = myimg.filename
if fname == "bob.jpeg" or fname == "sally.jpeg":
   do what the app needs to do
else:
   return "Only the demo images are allowed"

Obviously, restricting it by filename is silly because anyone can just rename a new file.

I was thinking perhaps that an image could be turned into some kind of special array, and then I can compare the two arrays, or is there a more elegant solution?

Any help/ideas are appreciated.

CodePudding user response:

To confirm whether the uploaded file is indeed the one you expect, simply examine its bytes and compare them to the known, good, file. You can either checksum the incoming bytes yourself (using, say, hashlib), or use filecmp.cmp (which I think is simpler, assuming you have a copy of the acceptable image on disk where the server can read it).

For example:

uploaded_img = request.files.get("myimg")
if not filecmp.cmp(uploaded_img.filename, "/path/to/known/good/image", shallow=False):
    raise ValueError("An unexpected file was uploaded")
  • Related