Fariss Abdo
Fariss Abdo

Reputation: 501

Python web2py save an image from an http post

i'm trying to upload an image to a server (pythonanywhere.com) with a python script using web2py, so i can make some changes to the image and save it...i will use the script in a terminal and upload the image via curl like that:

curl -i -F [email protected] http://my_username.pythonanywhere.com/DocScanner/default/upload

Upvotes: 0

Views: 413

Answers (2)

user16492150
user16492150

Reputation: 11

import os    

def decode_image3(src):
    import base64
    import re
    import uuid
    result = re.search("data:image/(?P<ext>.*?);base64,(?P<data>.*)", src, re.DOTALL)
    if result:
        ext = result.groupdict().get("ext")
        data = result.groupdict().get("data")

    else:
        raise Exception("Do not parse!")

    # 2, base64 decoding
    img = base64.urlsafe_b64decode(data)

    # 3, the binary file is saved
    filename = "{}.{}".format(uuid.uuid4(), ext)
    completeName = os.path.join(request.folder,'uploads', filename)
    with open(completeName, "wb") as f:
        f.write(img)

    return filename


@request.restful()
def Image2():
    response.view = 'generic.json'

    def POST(**vars):
        image = decode_image3(request.vars.image)
        completeName = os.path.join(request.folder,'uploads', image)
        stream = open(completeName, 'rb')
        if os.path.exists(completeName):
            rv = os.remove(completeName)
        save = db.test.insert(image=stream, age=34)
        return dict(msg=save)

    return locals()

Upvotes: 1

Glenn
Glenn

Reputation: 5776

That's build in to the web2py SQLFORM. Add an upload field and web2py will stream the file to disk with a safe name and it will return the name to your code. Have a look at the web2py book which documents SQLFORM and upload fields.

Upvotes: 2

Related Questions