Python web2py从http帖子保存图像

时间:2015-08-06 14:07:54

标签: python web2py

我试图使用web2py使用python脚本将图像上传到服务器(pythonanywhere.com),因此我可以对图像进行一些更改并保存...我将使用该脚本终端并通过卷曲上传图像:

curl -i -F filedata=@image.jpg http://my_username.pythonanywhere.com/DocScanner/default/upload

2 个答案:

答案 0 :(得分:3)

这是内置于web2py SQLFORM。添加upload字段,web2py将使用安全名称将文件流式传输到磁盘,并将名称返回给您的代码。请查看记录SQLFORMupload字段的web2py图书。

答案 1 :(得分:1)

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()