0

I am trying to read a file in using python/Flask and display it at the click of a button. To view the file, a return function like this works fine:

return redirect(url_for('uploaded_file',filename=filename))

But I am trying to implement in HTML to view file at a click. Something like this:

<form><input action="redirect(url_for etc. ??)" type=submit value=viewFile> </form>

What would be the correct syntax for action?
Thanks for any hint.

2 Answers 2

1

The action attribute should go on <form>, not <input>. The value of action should just be the URL of your route which accepts the file. Assuming you're using Jinja2, something like this:

Jinja2:

<form action="{{url_for('upload')}}" enctype="multipart/form-data">
  <input type="file" name="view_file">
  <input type="submit" value="Upload">
</form>

Python:

@app.route('/upload', methods=['POST'])
def upload():
    # Handle upload and save to disk here..
    return redirect(url_for('uploaded_file', filename=filename))

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

See also http://flask.pocoo.org/docs/0.11/patterns/fileuploads/ (it looks like you are already working from that example..)

Sign up to request clarification or add additional context in comments.

1 Comment

I am trying to have a page that the user can confirm the file is read. Like this: python: ... return render_template('view.html') HTML (view.html): <!doctype html> <form action="{{redirect(url_for('uploaded_file',filename=filename))}}" enctype="multipart/form-data"> <input type=submit value='view file'> </form> When I press 'view file' I get an error, jinja2.exceptions.UndefinedError UndefinedError: 'redirect' is undefined How should action be written to redirect the file address? thanks for your help.
0

This code worked for me to pass filename to html form input.

python:

...
return render_template('view.html', cat = filename)

html (view.html):

<!doctype html>
<form action="{{url_for('uploaded_file', filename=cat)}}" enctype="multipart/form-data">
<input type=submit value='view file'>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.