Python: Check if uploaded file is jpg

前端 未结 5 1162
-上瘾入骨i
-上瘾入骨i 2020-12-05 03:20

How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?

This is how far I got by now:

Script receives image via HTML F

5条回答
  •  情话喂你
    2020-12-05 04:08

    No need to use and install the PIL lybrary for this, there is the imghdr standard module exactly fited for this sort of usage.

    See http://docs.python.org/library/imghdr.html

    import imghdr
    
    image_type = imghdr.what(filename)
    if not image_type:
        print "error"
    else:
        print image_type
    

    As you have an image from a stream you may use the stream option probably like this :

    image_type = imghdr.what(filename, incomming_image)
    

    Actualy this works for me in Pylons (even if i have not finished everything) : in the Mako template :

    ${h.form(h.url_for(action="save_image"), multipart=True)}
    Upload file: ${h.file("upload_file")} 
    ${h.submit("Submit", "Submit")} ${h.end_form()}

    in the upload controler :

    def save_image(self):
        upload_file = request.POST["upload_file"]
        image_type = imghdr.what(upload_file.filename, upload_file.value)
        if not image_type:
            return "error"
        else:
            return image_type
    

提交回复
热议问题