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

example:

mkdir uploadfd

vi templates/upload.html

<html>
  <body>

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

  </body>
</html>

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

@ap.route('/upload')
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__':
  ap.run(host='0.0.0.0')

python upload.py

#opengttp://<ip/url>:5000/upload

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




Leave comments

authimage

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