Bootstrap FreeKB - Flask - Uploading files
Flask - Uploading files

Updated:   |  Flask articles

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

Let's say your Flask app has the following structure.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── upload.html
│   └── static (directory)
│       └── custom.css

 

And let's say the upload.html page perhaps has something like this, to allow users to upload a file.

 

The markup of the upload.html page could perhaps be as simple as this.

<form method="POST" action="/fileUpload" enctype="multipart/form-data">
  <input type="file" name="file1" >
  <input type="submit">
</form>

 

Here is how you could start to print the file being uploaded data.

@views.route('/test')
def home():
    print("request.files = " + str(request.files))
    file                 = request.files['file1']
    print("file          = " + str(file))
    print("file.filename = " + str(file.filename))
    filename             = secure_filename(file.filename)
    print("filename      = " + str(filename))
    return render_template('home.html')

 

Which should print the following.

request.files = ImmutableMultiDict([('file', <FileStorage: 'example.txt' ('text/plain')>)])
file          = <FileStorage: 'example.txt' ('text/plain')>
file.filename = example.txt
filename      = example.txt

 

In your view (views.py in this example) you could do something like this to render the home page (home.html in this example) and flash a message letting the user know if their image was successfully uploaded.

from flask import Blueprint, render_template, flash
from werkzeug.utils import secure_filename

@views.route('/')
def home():               
    return render_template('home.html')

@views.route('/fileUpload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
                
        if 'file' not in request.files:
            flash('Something got jacked up. It\'s me, not you. Sorry bout that.')
        else:
            file = request.files['file']

            if file.filename == '':
                flash('Did you forget to select a new file?')

            if file:       
                filename = secure_filename(file.filename)
                try:
                    file.save(os.path.join("/path/to/uploads/directory", filename))
                except Exception as exception:
                    print(exception)
                else:
                    flash('Success! Your new image has been uploaded. Lookin good you sexy thing!')
        
        return render_template('home.html')
    else:
        return render_template('upload.html')

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter d609b6 in the box below so that we can be sure you are a human.