**** file structure ********
.
├── templates
│ └── upload.html
├── upload
└── uploadfile.py
*** uploadfile.py code *******
from flask import render_template
from flask import Flask, request, redirect, url_for, send_from_directory
import os
from flask.ext.autoindex import AutoIndex
app = Flask(__name__)
AutoIndex(app, browse_root=os.path.curdir)
ufolder = "./upload"
app.config['Udir'] = ufolder
app.config['Fdir'] = 'files'
@app.route('/uploader', methods=['GET', 'POST'])
def uploader():
state = "welcome"
if request.method == 'POST':
# check if the post request has the file part
print request.files
if 'fileToUpload' not in request.files:
# flash('No file part')
state = 'nofile'
return render_template('./upload.html', state=state)
fileu = request.files['fileToUpload']
# if user does not select file, browser also
# submit a empty part without filename
if fileu.filename == '':
# flash('No selected file')
state = 'nofile'
return render_template('./upload.html', state=state)
# if fileu and allowed_file(fileu.filename):
else:
filename = fileu.filename
# filename = secure_filename(fileu.filename)
fileu.save(os.path.join(app.config['Udir'], filename))
# return redirect(url_for('uploaded_file',
# filename=filename))
state = 'uploaded'
return render_template('./upload.html', state=state)
else:
return render_template('./upload.html', state=state)
if __name__ == "__main__":
app.run()
*** upload.html code ******
<! DOCTYPE html>
<html>
<body>
<form method="post" action="/uploader" enctype="multipart/form-data">
{{ state }}
<br/>
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
1- to run it we can use
$ python uploadfile.py
it will listen to only localhost, port 5000
if you want it to listen on all interface run the following command
$ export FLASK_APP=uploadfile.py
$ python -m flask run --host=0.0.0.0
2- to access use the following url
http://localhost:5000
will get directory index
http://localhost:5000/uploadfile
will get you a upload form, and the file will be uploaded to folder upload.
No comments:
Post a Comment