How to read single file in my data using Flask

前端 未结 1 1606
别跟我提以往
别跟我提以往 2021-01-25 22:25

I\'m new in Flask, I want to take single file that have been uploaded in my upload path. Then i want to read and send it to my html after hr tag. How can i do that?

This

相关标签:
1条回答
  • 2021-01-25 22:54
    1. You need a variable route that will accept the a filename like @app.route('/<filename:filename>').
    2. You then need to get the file with that name from your upload directory like file_path = os.path.join('UPLOAD_PATH', filename).
    3. Then you need to read the contents of that file and pass it into your view.
    with open(file_path) as file:
        content = file.read()
    
    1. Then you can access it in your HTML file and display it.
    <p>{{ content }}</p>
    

    Here is a complete example of the route I described:

    @app.route('/<filename:filename>')
    def display_file(filename):
        file_path = os.path.join('UPLOAD_PATH', filename)
        with open(file_path) as file:
            content = file.read()
        return render_template('display_file.html', content=content)
    
    0 讨论(0)
提交回复
热议问题