python flask restfull receive image

w40 picture w40 · Nov 9, 2017 · Viewed 8.6k times · Source

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

Answer

georgexsh picture georgexsh · Nov 13, 2017

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.