Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flask upload example
<VirtualHost *>
ServerName example.com
WSGIDaemonProcess www user=max group=max threads=5
WSGIScriptAlias / /home/max/Projekte/flask-upload/flask-upload.wsgi
<Directory /home/max/Projekte/flask-upload>
WSGIProcessGroup www
WSGIApplicationGroup %{GLOBAL}
Order deny,allow
Allow from all
</Directory>
</VirtualHost>
activate_this = '/home/max/.virtualenvs/flask/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
import sys
sys.path.insert(0, '/home/max/Projekte/flask-upload')
from server import app as application
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
UPLOAD_FOLDER = '/tmp/'
ALLOWED_EXTENSIONS = set(['txt'])
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('index'))
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>
<p>%s</p>
""" % "<br>".join(os.listdir(app.config['UPLOAD_FOLDER'],))
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5001, debug=True)
@swdevbali

This comment has been minimized.

Show comment
Hide comment
@swdevbali

swdevbali Mar 16, 2014

I love this gist. Clearly show how file uploading works in Flask.
Thanks @dAnjou!

swdevbali commented Mar 16, 2014

I love this gist. Clearly show how file uploading works in Flask.
Thanks @dAnjou!

@casatwy

This comment has been minimized.

Show comment
Hide comment
@casatwy

casatwy commented Jun 18, 2014

thanks! @dAnjou

@saadkh225

This comment has been minimized.

Show comment
Hide comment
@saadkh225

saadkh225 commented Jul 17, 2014

Ty @dAnjou

@bhadley

This comment has been minimized.

Show comment
Hide comment
@bhadley

bhadley commented Jul 29, 2014

Thanks!

@wangyu190810

This comment has been minimized.

Show comment
Hide comment
@wangyu190810

wangyu190810 commented Mar 11, 2015

Thanks

@Thuruv

This comment has been minimized.

Show comment
Hide comment
@Thuruv

Thuruv May 29, 2015

Extremely awesome. Thanks a bunch.

Thuruv commented May 29, 2015

Extremely awesome. Thanks a bunch.

@jzp113

This comment has been minimized.

Show comment
Hide comment
@jzp113

jzp113 Sep 7, 2015

I fellow your code ,when I upload file is normal but I can not found the file in dir

jzp113 commented Sep 7, 2015

I fellow your code ,when I upload file is normal but I can not found the file in dir

@mrmagcore

This comment has been minimized.

Show comment
Hide comment
@mrmagcore

mrmagcore Nov 11, 2015

How do you get form data? When I add a line like this:

item_name = request.form['name']

flask throws a 400

mrmagcore commented Nov 11, 2015

How do you get form data? When I add a line like this:

item_name = request.form['name']

flask throws a 400

@bakztfuture

This comment has been minimized.

Show comment
Hide comment
@bakztfuture

bakztfuture Jan 23, 2016

@mrmagcore I was able to get the form data by putting name='name' in the html form, as opposed to id='name'. In flask, I was able to access the POST data via name = request.form.getlist('name')

bakztfuture commented Jan 23, 2016

@mrmagcore I was able to get the form data by putting name='name' in the html form, as opposed to id='name'. In flask, I was able to access the POST data via name = request.form.getlist('name')

@d33tah

This comment has been minimized.

Show comment
Hide comment
@d33tah

d33tah Feb 21, 2016

Thanks! A coding style suggestion: could you change the pattern:

if allowed_filename(...):
    # code

To:

if not allowed_filename(...):
    return error

# code goes unindented here

d33tah commented Feb 21, 2016

Thanks! A coding style suggestion: could you change the pattern:

if allowed_filename(...):
    # code

To:

if not allowed_filename(...):
    return error

# code goes unindented here
@gaoning777

This comment has been minimized.

Show comment
Hide comment
@gaoning777

gaoning777 Jul 25, 2016

thanks a lot, having a hard time to do this

gaoning777 commented Jul 25, 2016

thanks a lot, having a hard time to do this

@ghost

This comment has been minimized.

Show comment
Hide comment
@ghost

ghost Sep 27, 2016

fanks you!

ghost commented Sep 27, 2016

fanks you!

@dardan

This comment has been minimized.

Show comment
Hide comment
@dardan

dardan Oct 27, 2016

What if we want to rename a file if it allreade exists ;), here is How

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = '/tmp/'
ALLOWED_EXTENSIONS = set(['txt'])

app = Flask(name)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
return '.' in filename and
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def filenamechanger(filename):
if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
myfilename = filename.split('.')
if len(myfilename[0].split(''))>2:
a = myfilename[0].split('
')
a.pop()
b = []
for xk in range(0,len(a)):
if xk < len(a)-1:
b.append(''.join([a[xk],'']))
else:
b.append(a[xk])
myfilename[0] = ''.join(b)
print(myfilename)
i = 0
sexer = filename
while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], sexer)):
sexer = ''.join([myfilename[0],'
',str(i),'.',myfilename[1]])
print(sexer)
i+= 1
filename = sexer
return filename
return filename

@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filename = filenamechanger(filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
print('My Filename: ',filename)
return redirect(url_for('index'))
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> <p>%s</p>""" %<br> "".join(os.listdir(app.config['UPLOAD_FOLDER'],))

if name == 'main':
app.run(
host="0.0.0.0",
port=int("80"),
debug=True
)

dardan commented Oct 27, 2016

What if we want to rename a file if it allreade exists ;), here is How

import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = '/tmp/'
ALLOWED_EXTENSIONS = set(['txt'])

app = Flask(name)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
return '.' in filename and
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def filenamechanger(filename):
if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
myfilename = filename.split('.')
if len(myfilename[0].split(''))>2:
a = myfilename[0].split('
')
a.pop()
b = []
for xk in range(0,len(a)):
if xk < len(a)-1:
b.append(''.join([a[xk],'']))
else:
b.append(a[xk])
myfilename[0] = ''.join(b)
print(myfilename)
i = 0
sexer = filename
while os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], sexer)):
sexer = ''.join([myfilename[0],'
',str(i),'.',myfilename[1]])
print(sexer)
i+= 1
filename = sexer
return filename
return filename

@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
filename = filenamechanger(filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
print('My Filename: ',filename)
return redirect(url_for('index'))
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> <p>%s</p>""" %<br> "".join(os.listdir(app.config['UPLOAD_FOLDER'],))

if name == 'main':
app.run(
host="0.0.0.0",
port=int("80"),
debug=True
)

@sharadbhat

This comment has been minimized.

Show comment
Hide comment
@sharadbhat

sharadbhat Oct 5, 2017

THANK YOU!

sharadbhat commented Oct 5, 2017

THANK YOU!

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