简体   繁体   English

python flask restfull接收图像

[英]python flask restfull receive image

Hi I am having trouble receiving a file on my flask server from my python client I am saving the screenshot in memory but am unable to receive it on the server end. 嗨,我在从python客户端接收烧瓶服务器上的文件时遇到问题,我将屏幕截图保存在内存中,但是无法在服务器端接收到。 I appreciate any help I can get I am lost with what my requests.post has to be. 我很感激我能得到的任何帮助,让我迷失了我所要求的。

Server Code: 服务器代码:

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

Client Code: 客户代码:

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)

file to upload should be in format ('filename', fileobj, 'content_type') , so change 要上传的文件应采用以下格式('filename', fileobj, 'content_type') ,因此请更改

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM