FileStorage contains stream field. This object must extend IO or file object, so it must contain read and other similar methods. FileStorage also extend stream field object attributes, so you can just use file.read() instead file.stream.read(). Also you can use save argument with dst parameter as StringIO or other IO or file object to copy FileStorage.stream to another IO or file object.

See documentation: http://flask.pocoo.org/docs/api/#flask.Request.files and http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage.

Answer from tbicr on Stack Overflow
๐ŸŒ
Miguel Grinberg
blog.miguelgrinberg.com โ€บ post โ€บ handling-file-uploads-with-flask
Handling File Uploads With Flask - miguelgrinberg.com
July 8, 2020 - In the app I'm building (which ... used the flask-uploads library to upload image files as well as csv files. Looking at this tutorial, I'm wondering if I should refactor it to be simpler? ... I certainly do not want to force anybody to do anything, but I really like those "advanced" boxes in books, which give an offer to the reader: "read when ...
Discussions

Processing an uploaded file without saving it

Data uploaded via a FileField in a FlaskForm (the data thats in form.photo.data in your example) is represented as a FileStorage object. According to the documentation, instead of doing f.save(...), you also can do f.read() to access that data.

More on reddit.com
๐ŸŒ r/flask
4
14
April 25, 2019
python - How to read uploaded file data without saving it in Flask? - Stack Overflow
First uploading a file using html form. I don't want to store that file in the project directory. Without saving how can I read all the file contents? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Opening an uploaded file in Flask
What is your code for handling the upload in Flask? More on reddit.com
๐ŸŒ r/learnpython
6
4
February 10, 2017
How to create a Flask FileStorage.read() object for testing
I am trying to write a test for a function that uses a file that has been uploaded through http and that read using flask, for example: content = flask.request.files["myfile"].read() I am not totally clear how this works,I understand that flask would output FileStorage objects but I am not ... More on discuss.python.org
๐ŸŒ discuss.python.org
0
0
February 7, 2023
๐ŸŒ
Python Basics
pythonbasics.org โ€บ flask-upload-file
Upload a File with Python Flask - Python Tutorial
It requires an HTML form whose enctype property is set to "multipart/form-data" to publish the file to the URL.The URL handler extracts the file from the request.files [] object and saves it to the required location. Related course: Python Flask: Create Web Apps with Flask ยท Each uploaded file ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ flask โ€บ flask_file_uploading.htm
Flask File Uploading
from flask import Flask, render_template, request from werkzeug import secure_filename app = Flask(__name__) @app.route('/upload') def upload_file(): return render_template('upload.html') @app.route('/uploader', methods = ['GET', 'POST']) def upload_file(): if request.method == 'POST': f = request.files['file'] f.save(secure_filename(f.filename)) return 'file uploaded successfully' if __name__ == '__main__': app.run(debug = True)
๐ŸŒ
Flask
flask.palletsprojects.com โ€บ en โ€บ stable โ€บ patterns โ€บ fileuploads
Uploading Files โ€” Flask Documentation (3.1.x)
This feature was added in Flask 0.6 but can be achieved in older versions as well by subclassing the request object. For more information on that consult the Werkzeug documentation on file handling. A while ago many developers had the idea to read the incoming file in small chunks and store the upload ...
๐ŸŒ
Medium
medium.com โ€บ featurepreneur โ€บ uploading-files-using-flask-ec9fb4c7d438
Uploading files using Flask
May 14, 2021 - You will also be able to see the contents of the file which you just uploaded displayed on your screen. GitHub Link โ€” https://github.com/Hilda24/Flask-file-upload
๐ŸŒ
Webscale
section.io โ€บ home โ€บ blog
How to Handle File Uploads with Flask
June 24, 2025 - Get the latest insights on AI, personalization, infrastructure, and digital commerce from the Webscale team and partners.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/flask โ€บ processing an uploaded file without saving it
r/flask on Reddit: Processing an uploaded file without saving it
April 25, 2019 -

Trying to have client upload csv file via WTF in my Flask app, process the contents and not save it anywhere. Based on the documentation example, it focused on saving it. Any recommendations here on how to read the contents of say form.myfile.data without saving it?

@app.route('/upload', methods=['GET', 'POST']) def upload(): if form.validate_on_submit(): f = form.photo.data filename = secure_filename(f.filename) f.save(os.path.join( app.instance_path, 'photos', filename )) return redirect(url_for('index'))

return render_template('upload.html', form=form)
Top answer
1 of 1
4

If you want only to read data from file then simply use .read()

uploaded_file = request.files.get('uploaded_file')

data = uploaded_file.read()

print(data)

And if you want to use it with function which needs filename then usually it may work also with file-like object and you can use it directly

ie. Pillo.Image

from PIL import Image

uploaded_file = request.files.get('uploaded_file')

img = Image.open(uploaded_file)
img.save('new_name.jpg')

ie. pandas.DataFrame

import pandas as pd

uploaded_file = request.files.get('uploaded_file')

df = pd.read_csv(uploaded_file)

You can also use io.BytesIO() to create file-like object in memory.

from PIL import Image
import io

uploaded_file = request.files.get('uploaded_file')

data = uploaded_file.read()

file_object = io.BytesIO(data)
#file_object.seek(0)

img = Image.open(file_object)
img.save('new_name.jpg')
import pandas as pd
import io

uploaded_file = request.files.get('uploaded_file')

data = uploaded_file.read()

file_object = io.BytesIO(data)
#file_object.seek(0)

df = pd.read_csv(file_object)

But this is more useful when you want to save/generate data without writing on disk and later send it back to browser.

uploaded_file = request.files.get('uploaded_file')

img = Image.open(uploaded_file)

# generate smaller version
img.thumbnail((200,200))

# write in file-like object as JPG
file_object = io.BytesIO()
img.save(file_object, 'JPEG')

# get data from file
data = file_object.getvalue()  # get data directly
# OR
#file_object.seek(0)           # move to the beginning of file after previous writing/reading
#data = file_object.read()     # read like from normal file

# send to browser as HTML
data = base64.b64encode(data).decode()
html = f'<img src="data:image/jpg;base64, {data}">'
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ opening an uploaded file in flask
r/learnpython on Reddit: Opening an uploaded file in Flask
February 10, 2017 -

Hi all, I'm trying to modify a csv that is uploaded into my flask application. I have the logic that works just fine when I don't upload it through flask.

    import pandas as pd
    import StringIO
    with open('example.csv') as f:
        data = f.read()

    data = data.replace(',"', ",'")
    data = data.replace('",', "',")
    df = pd.read_csv(StringIO.StringIO(data), header=None, sep=',', quotechar="'")
    print df.head(10)

When I use a site to upload the file and try and run the above I get

coercing to Unicode: need string or buffer, FileStorage found

I have figured out that the problem is the file type here. I can't use open on my file because open is looking for a file name and when the file is uploaded to flask it is the instance of the file that is being passed to the open command. However, I don't know how to make this work. I've tried skipping the open command and just using data = f.read() but that doesn't work. Any suggestions?

Thanks

๐ŸŒ
YouTube
youtube.com โ€บ watch
Uploading and Returning Files With a Database in Flask - YouTube
Learn how to upload files to Flask and save to and retrieve from a BLOB column using SQLAlchemy.Want to level up your Flask skills? My full course, The Ultim...
Published ย  January 22, 2022
๐ŸŒ
Readthedocs
flask-uploads.readthedocs.io
Flask-Uploads โ€” Flask-Uploads 0.1.1 documentation
Continuing the example above, if /var/uploads is accessible from http://localhost:5001, then you would set this to http://localhost:5001/ and URLs for the photos set would start with http://localhost:5001/photos. Include the trailing slash. However, you donโ€™t have to set any of the _URL settings - if you donโ€™t, then they will be served internally by Flask.
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to create a Flask FileStorage.read() object for testing - Python Help - Discussions on Python.org
February 7, 2023 - I am trying to write a test for a function that uses a file that has been uploaded through http and that read using flask, for example: content = flask.request.files["myfile"].read() I am not totally clear how this worโ€ฆ
Top answer
1 of 1
3

You already saved it here

file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

just open it up and read as you work with any other files, example:

@app.route('/read_file', methods=['GET'])
def read_uploaded_file():
    filename = secure_filename(request.args.get('filename'))
    try:
        if filename and allowed_filename(filename):
            with open(os.path.join(app.config['UPLOAD_FOLDER'], filename)) as f:
                return f.read()
    except IOError:
        pass
    return "Unable to read file"

You need to carefully sanitize user input here, otherwise method could be used to read something unintended (like app source code for example). Best is just not grant user ability to read arbitrary files - for example when you save a file, store it's path in database with some token and give user just this token:

filename = secure_filename(file.filename)
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
token = store_in_db(filepath)
return redirect(url_for('read_uploaded_file',
                                   token=token))

Then accept a token, not a filename when you read a file:

@app.route('/read_file', methods=['GET'])
def read_uploaded_file():
    filepath = get_filepath(request.args.get('token'))
    try:
        if filepath and allowed_filepath(filepath):
            with open(filepath) as f:
                return f.read()
    except IOError:
        pass
    return "Unable to read file"

Tokens need to be random, long, not guessable (uuid4 for example) - otherwise there will be a possibility to easily read other users files. Or you need to store relation between file and user in database and check it too. Finally, you need to control size of file uploads to prevent user from uploading huge files (app.config['MAX_CONTENT_LENGTH']) and control amount of info you read in memory when you display "filtered" file content (f.read(max_allowed_size)).

๐ŸŒ
GitHub
hplgit.github.io โ€บ web4sciapps โ€บ doc โ€บ pub โ€บ ._web4sa_flask016.html
Github
October 11, 2015 - We assume that the uploaded file is available in the uploads subdirectory, so the compute function needs to open this file, read the numbers, and compute statistics. The file reading and computations are easily done by numpy functions.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 63333032 โ€บ how-to-read-single-file-in-my-data-using-flask
python - How to read single file in my data using Flask - Stack Overflow
You then need to get the file with that name from your upload directory like file_path = os.path.join('UPLOAD_PATH', filename). Then you need to read the contents of that file and pass it into your view.
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ flask file uploading โ€“ create a form in python flask to upload files
Flask File Uploading - Create a Form in Python Flask to Upload Files - AskPython
September 14, 2020 - The Upload View then stores the file temporarily in the variable f before permanently saving it with the f.save() attribute. Do check out our Flask Forms article to know more about forms in Flask.
๐ŸŒ
ProgramCreek
programcreek.com โ€บ python โ€บ example โ€บ 51528 โ€บ flask.request.files
Python Examples of flask.request.files
def upload_file(): file = request.files['pcap'] if file and allowed_file(file.filename): hash = hashlib.sha256() try: # FIXME: it should be saved before calculate sha256 hash.update(file.read()) except: print "Unexpected error:", sys.exc_info() finally: file.seek(0) hash_name = "%s" % (hash.hexdigest()) file.save(os.path.join(app.config['UPLOAD_FOLDER'], hash_name)) pcap = {'id' : hash_name, 'date' : datetime.datetime.utcnow()} pcap_id = db.pcap.insert(pcap) return redirect(url_for('launch', pcap_id=pcap_id))