Guest User

Flask docs file upload example + hello world

a guest
Jan 18th, 2021
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. import os
  2. from flask import Flask, flash, request, redirect, url_for
  3. from werkzeug.utils import secure_filename
  4.  
  5. UPLOAD_FOLDER = './uploads/'
  6. ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
  7.  
  8. app = Flask(__name__)
  9. app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
  10. app.config['SECRET_KEY'] = 'mysecretkey'
  11.  
  12. @app.route('/')
  13. def hello_world():
  14.     return 'Hello, world!'
  15.  
  16. def allowed_file(filename):
  17.     return '.' in filename and \
  18.            filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
  19.  
  20. @app.route('/upload', methods=['GET', 'POST'])
  21. def upload_file():
  22.     if request.method == 'POST':
  23.         # check if the post request has the file part
  24.         if 'file' not in request.files:
  25.             print('No file part')
  26.             return redirect(request.url)
  27.         file = request.files['file']
  28.         # if user does not select file, browser also
  29.         # submit an empty part without filename
  30.         if file.filename == '':
  31.             print('No selected file')
  32.             return redirect(request.url)
  33.         if file and allowed_file(file.filename):
  34.             filename = secure_filename(file.filename)
  35.             file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
  36.             return redirect(url_for('upload_file',
  37.                                     filename=filename))
  38.     return '''
  39.    <!doctype html>
  40.    <title>Upload new File</title>
  41.    <h1>Upload new File</h1>
  42.    <form method=post enctype=multipart/form-data>
  43.      <input type=file name=file>
  44.      <input type=submit value=Upload>
  45.    </form>
  46.    '''
Advertisement
Add Comment
Please, Sign In to add comment