Web.py POST StringIO 用PIL打开

POST发送数据:

python# encoding:utf-8
import requests
from StringIO import StringIO

img = open('test.jpg').read()
img = StringIO(img)
files = {'img': img}
baseUrl = r'http://localhost:8080/test'
requests.post(baseUrl, files = files)

在web.py里

pythonimport web
from PIL import Image
urls = ('/test', 'Test')

class Test:

    def GET(self):
        pass
    def POST(self):
        data = web.input()
        # 如何用PIL打开获取来的StringIO?
        img = Image.open(StringIO(data.img)) # 报错

线谢谢各位了。

阅读 3k
评论
    2 个回答

    upload.py

    import requests
    
    r = requests.post('http://127.0.0.1:8080/upload', files={
        'img': open('test.png', 'rb')
    })
    print r.text
    

    main.py (儲存圖片到指定路徑並另存縮圖)

    # -*- coding: utf-8 -*-
    import uuid
    import re
    import web
    from PIL import Image
    
    urls = {
        '/upload', 'Upload'
    }
    
    
    class Upload:
        def __init__(self):
            self.upload_dir = "./upload"
    
        def GET(self):
            pass
    
        def POST(self):
            data = web.input(img={})
    
            if 'img' in data:
                filepath = data.img.filename.replace('\\', '/')
                extension = filepath.rsplit(".", 1)[1]
                extension = re.sub("[^a-zA-Z0-9]", "", extension).lower()
                filename = str(uuid.uuid4()) + "." + extension
                fout = open(self.upload_dir + '/' + filename, 'w')
                fout.write(data.img.file.read())
                fout.close()
    
                self.thumbnail(filename)
                return "ok"
    
        def thumbnail(self, filename):
            img = Image.open(self.upload_dir + '/' + filename)
            img.thumbnail((256, 256))
            img.save(self.upload_dir + '/thumbnail/' + filename)
    
    
    if __name__ == "__main__":
        app = web.application(urls, globals())
        app.run()
    
      • 5
      • 新人请关照

      你得把报的具体错误贴上来。
      不看错误内容就来问。。。有时候可能是个很简单的错误,比如在接收post过来的参数的时候data.files.img写成了data.img之类的

        撰写回答

        登录后参与交流、获取后续更新提醒

        相似问题
        推荐文章