Uploading a text file in Flask and reading it in html

Viewed 1694

I'm trying to upload a simple text file and then display it in another URL in flask. However, I'm getting a blank output with b" as the only thing showing. Its just a regular text file with utf-8.

Here's the code -

def upload_source():
if request.method == 'POST':
    # check if the post request has the file part
    f = request.files['file']
    if f.filename == "":
        print("No file Name")
        return redirect(request.url)
    if not allowed_file(f.filename):
        print("File extension not allowed!")
        return redirect(request.url)
    else:
        full_filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], full_filename))
        print("File saved")
        content = f.read()
        return render_template('source.html', text=content)

and i'm including this in the source html

<p> {{ text }} </p>

I'm relatively new to python and flask and I appreciate your help here. Thank you!

1 Answers

Thanks to the commenters on this post, I could come up with a fix to this. Initially, I was getting a b" as the only output after using only f.read().

When I used f.seek(0), I got the output of my text file but with a lot of encoding and formatting errors, including a new preceding b` followed by my output.

But adding content = f.read()
content = str(content, 'utf-8') fixed most of that aswell.

So here goes the final solution-

def upload_source():
if request.method == 'POST':
    # check if the post request has the file part
    f = request.files['file']
    if f.filename == "":
        print("No file Name")
        return redirect(request.url)
    if not allowed_file(f.filename):
        print("File extension not allowed!")
        return redirect(request.url)
    else:
        full_filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], full_filename))
        f.seek(0)
        print("File saved")
        content = f.read()
        content = str(content, 'utf-8')
        return render_template('source.html', text=content)

and don't forget the same old HTML -

<p> {{ text }} </p>

I hope this can help others as well. Thank you!

Related