Flask File Uploads Uploading Files


Example

HTML Form

  • Use a file type input and the browser will provide a field that lets the user select a file to upload.
  • Only forms with the post method can send file data.
  • Make sure to set the form's enctype=multipart/form-data attribute. Otherwise the file's name will be sent but not the file's data.
  • Use the multiple attribute on the input to allow selecting multiple files for the single field.
<form method=post enctype=multipart/form-data>
    <!-- single file for the "profile" field -->
    <input type=file name=profile>
    <!-- multiple files for the "charts" field -->
    <input type=file multiple name=charts>
    <input type=submit>
</form>

Python Requests

Requests is a powerful Python library for making HTTP requests. You can use it (or other tools) to post files without a browser.

  • Open the files to read in binary mode.
  • There are multiple data structures that files takes. This demonstrates a list of (name, data) tuples, which allows multiple files like the form above.
import requests

with open('profile.txt', 'rb') as f1, open('chart1.csv', 'rb') as f2, open('chart2.csv', 'rb') as f3:
    files = [
        ('profile', f1),
        ('charts', f2),
        ('charts', f3)
    ]
    requests.post('http://localhost:5000/upload', files=files)

This is not meant to be an exhaustive list. For examples using your favorite tool or more complex scenarios, see the docs for that tool.