How to pass uploaded image to template.html in Flask

前端 未结 2 1797
旧巷少年郎
旧巷少年郎 2020-12-04 17:03

I am using flask, and trying to do something very simple using the quickstart tutorial, just running on my machine (local server). I produce a simple upload form which succe

相关标签:
2条回答
  • 2020-12-04 17:37

    From the uploaded_file function, we head to the template.html and there will are redirected back <img src="{{ url_for('send_file', filename=filename) }}"> coming back we hit the send_file function which will show the content of the HTML inside the template with image uploaded and stored in the UPLOAD_FOLDER specified. you are also missing from werkzeug import secure_filename this in py file

    @app.route('/show/<filename>')
    def uploaded_file(filename):
        return render_template('template.html', filename=filename)
    
    @app.route('/uploads/<filename>')
    def send_file(filename):
        return send_from_directory(UPLOAD_FOLDER, filename)
    

    Now your template.html will look like this..

    <!doctype html>
    <title>Hello from Flask</title>
    {% if filename %}
      <h1>some text <img src="{{ url_for('send_file', filename=filename) }}">more text!</h1>
    {% else %}
      <h1>no image for whatever reason</h1>
    {% endif %}
    
    0 讨论(0)
  • 2020-12-04 17:39

    What's happening now is that /uploads/foo.jpg returns the HTML inside template.html. There you try to use /uploads/foo.jpg as the source of the img tag. Nowhere you serve the actual image out.

    Let's modify it like this: /show/foo.jpg returns the HTML page and and /uploads/foo.jpg returns the image. Replace the latter route with these two and you should be good to go:

    @app.route('/show/<filename>')
    def uploaded_file(filename):
        filename = 'http://127.0.0.1:5000/uploads/' + filename
        return render_template('template.html', filename=filename)
    
    @app.route('/uploads/<filename>')
    def send_file(filename):
        return send_from_directory(UPLOAD_FOLDER, filename)
    
    0 讨论(0)
提交回复
热议问题