1

Hellow. Is there any way to open file in browser using Flask ? I can read the content of the file and then return this content into page using:

@app.route('/open', methods=['GET', 'POST'])
def open():    
file = urllib.request.urlopen('file:///C:/app/files/file.txt')
content = file.read()
return content

instead of it I want to force browser (Google Chrome) to open this file using it's built-in functionality, because my file is not '.txt'. Usually it's '.docx', or '.pdf'. Is there flask method to implent something like this?

V.Nosov
  • 93
  • 3
  • 10

1 Answers1

2

Try to return the PDF file with mimetype like the below

from flask import send_from_directory
@app.route('/open', methods=['GET', 'POST'])
    def open():    
    return send_from_directory(directory='some_directory',
                           filename='filename',
                           mimetype='application/pdf')

You can't open docx files in your browser because browsers cannot render or read these files. If you still want to do this you will have to use Google docs in an iframe or other solutions

You can refer to this answer: How do I render a Word document (.doc, .docx) in the browser using JavaScript?

shifloni
  • 719
  • 4
  • 7
  • Actually, I can open docx files with my browser (Google Chrome, maybe it's an extension i don't know exactly). Only for reading, but it's enough. Thank you, it works!!! – V.Nosov Aug 24 '18 at 16:19