素材牛VIP会员
Web.py POST StringIO 用PIL打开
 躺***上  分类:Python  人气:730  回帖:2  发布于6年前 收藏

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)) # 报错

线谢谢各位了。

 标签:web.pypython

讨论这个帖子(2)垃圾回帖将一律封号处理……

Lv4 码徒
阿***q 站长 6年前#1

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()
Lv1 新人
陌***人 PHP开发工程师 6年前#2

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

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取