python flask restfull接收图像

时间:2017-11-09 06:50:23

标签: python flask stringio

您好我从我的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)

1 个答案:

答案 0 :(得分:4)

file to upload should be in format ('filename', fileobj, 'content_type'), so change

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

to

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

doc ref:

files -- (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.