I got a web service that allows user to upload files to the "Uploads" folder. These files are accessible by name using the /uploads/filename.ext path. However, unless I know the precise filename, I cannot access files.
How can I programmatically generate and serve a webpage that will provide an index of all files in the /uploads folder if the user types /uploads?
from flask import Flask
from flask import Response, jsonify, request, redirect, url_for
import os
from werkzeug.utils import secure_filename
#configuration
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#retrieve uploads by name
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
################# AUDIO NOTES UPLOAD ####################
@app.route('/', methods=['GET', 'POST'])
def upload_file():
print 'upload file'
try:
os.stat(app.config['UPLOAD_FOLDER'])
except:
os.mkdir(app.config['UPLOAD_FOLDER'])
if request.method == 'POST':
file = request.files['file']
print 'filename: ' + file.filename
if file and allowed_file(file.filename):
print 'allowing file'
filename = secure_filename(file.filename)
print 'secure filename created'
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print 'file saved'
return redirect(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 LAUNCH POINT ############################
if __name__ == '__main__':
app.run(host='0.0.0.0')
############################################################