【问题标题】:python flask restfull receive imagepython flask restful 接收图像
【发布时间】:2018-04-22 01:53:49
【问题描述】:

您好,我在从我的 python 客户端接收我的烧瓶服务器上的文件时遇到问题我正在将屏幕截图保存在内存中,但无法在服务器端接收它。感谢我能得到的任何帮助

服务器代码:

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    filename = secure_filename(file.filename)
    file.save(os.path.join(app.config['upload_folder'], filename))

客户代码:

content_type = 'image/jpeg'
headers = {'content-type': content_type}

from PIL import ImageGrab
from StringIO import StringIO
screen = ImageGrab.grab()
img = stringIO()
screen.save(img, 'JPEG')
img.seek(0)
fd = open('screen.jpg', 'wb')
fd.write(img.getvalue())
fd.close()
fin = open('screen.jpg', 'wb')
files = {'file': fin}
requests.post('http://localhost/upload', files=files)

【问题讨论】:

  • files={'file': ('test.jpg', content_type)}你的图片数据在哪里?
  • 感谢您的回复我已经更新了代码,并且可以将图像保存到磁盘并毫无问题地发布,但我想了解如何在不将其保存到磁盘的情况下仍然可以发布图像。

标签: python flask stringio


【解决方案1】:

要上传的文件格式应该是('filename', fileobj, 'content_type'),所以改一下

files={'file': ('test.jpg', content_type)}

files={'file': ('test.jpg', img, content_type)}

文档参考:

files -- (可选)“名称”字典:类似文件的对象(或 {'name': file-tuple}) 用于多部分编码上传。文件元组可以是 一个 2 元组 ('filename', fileobj), 3 元组 ('filename', fileobj, 'content_type') 或 4 元组 ('filename', fileobj, 'content_type', custom_headers),其中 'content-type' 是定义内容的字符串 给定文件的类型和 custom_headers 一个类似字典的对象 包含要为文件添加的其他标题。

【讨论】:

  • 您好,非常感谢您的回答和文档,我确实错过了我的错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2017-02-25
  • 2015-05-13
  • 2020-11-08
  • 2015-07-26
  • 2017-02-24
相关资源
最近更新 更多