Skip to content

Instantly share code, notes, and snippets.

@yoavram
Created December 21, 2012 08:41
Show Gist options
  • Save yoavram/4351498 to your computer and use it in GitHub Desktop.
Save yoavram/4351498 to your computer and use it in GitHub Desktop.
Example of uploading binary files programmatically in python, including both client and server code. Client implemented with the requests library and the server is implemented with the flask library.
import requests
#http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file
url = "http://localhost:5000/"
fin = open('simple_table.pdf', 'rb')
files = {'file': fin}
try:
r = requests.post(url, files=files)
print r.text
finally:
fin.close()
# http://flask.pocoo.org/docs/patterns/fileuploads/
import os
from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
# this has changed from the original example because the original did not work for me
return filename[-3:].lower() in ALLOWED_EXTENSIONS
@app.route('/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
print '**found file', file.filename
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# for browser, add 'redirect' function on top of 'url_for'
return url_for('uploaded_file',
filename=filename)
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
'''
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
if __name__ == '__main__':
app.run(debug=True)
@mohammedlutf
Copy link

what if i want to send a file from a server to client

@nurettin
Copy link

@mohammelutf for web clients, you could do a server push using server sent events, websockets, long-polling or polling. For non-web clients, you could use redis pub/sub, a rabbitmq fanout exchange, an mqtt channel or zmq router-dealer, plain old tcp or even mounting nfs.

@bzhao
Copy link

bzhao commented Jul 15, 2020

From Windows 7, I cannot upload the file whose name is Chinese font.
In my case, it is: 无标题.png
After uploading is finished, it is saved as .png file in the "uploads" folder

@yoavram
Copy link
Author

yoavram commented Jul 15, 2020

The code is in python 2, try to use python 3 which has better support for Unicode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment