Flask File Uploading

an HTML form with its enctype attribute set to 'multipart/form-data'
request.files[]: fetches file and saves it to the desired location
secure_filename(): read the file name with a more secure method

app.config[‘UPLOAD_FOLDER’]: Defines path for upload folder
app.config[‘MAX_CONTENT_LENGTH’]: Specifies maximum size of file yo be uploaded – in bytes


mkdir uploadfd

vi templates/upload.html


    <form action = "/uploadfd" method = "POST"
      enctype = "multipart/form-data">
      <input type = "file" name = "file" />
      <input type = "submit" value="upload"/>


vi upload.py
from flask import Flask, render_template, request
from werkzeug import secure_filename
ap = Flask(__name__)

def upload():
  return render_template('upload.html')

@ap.route('/uploadfd', methods = ['GET', 'POST'])
def upload_file():
  if request.method == 'POST':
    f = request.files['file']
    f.save('uploadfd/' + secure_filename(f.filename))
    return 'file uploaded successfully'

if __name__ == '__main__':

python upload.py


secure_filename can't save not ASCII file name, must do some modify,
but how to do?...

Leave comments


Copyright(c) 2017 - PythonBlogs.com
By using this website, you signify your acceptance of Terms and Conditions and Privacy Policy
All rights reserved