Search code examples
pythonhtmlflask

How to Display Image in Flask after a button is pressed


I am new to flask and web development. I want to display an image on a local web server after I press a button on the webpage. I am using Flask.Ive been trying to figure this out for a while and havent been able too so any help would be incredible. FLASK CODE:

@app.route('/graph_select')
def graph_select():
    return render_template('live_stream.html')


@app.route('/read_ph', methods=["GET"])
def ph_plot():
    if request.method == "GET":
        all_plots.ph_plot()
        return render_template('live_stream.html')


@app.route("/read_temp", methods=["GET"])
def temp_plot():
    if request.method == "GET":
        all_plots.temperature_plot()
        return render_template('live_stream.html')


@app.route('/read_distance', methods=["GET"])
def distance_plot():
    if request.method == "GET":
        all_plots.distance_plot()
        return render_template('live_stream.html')

HTML CODE:

    <h1>Data Monitoring Station</h1>

      <form method="GET" 
        <a href="read_temp"><button type="button">Temperature Graph</button></a>
        <a href="read_ph"><button type="button">PH Graph</button></a>
        <a href="read_distance"><button type="button">Distance Graph</button></a>
      </form>

    <h3><img src="{{ url_for('static', filename='ph_plot.png') }}" width="30%">$
    <h3><img src="{{ url_for('static', filename='temperature_plot.png') }}" width="30%">$
    <h3><img src="{{ url_for('static', filename='distance_plot.png') }}" width="30%">$




  </body>
</html>

Solution

  • TLDR;

    I wrote a minimal example on displaying images on button click using Flask and Ajax.

    In essence, I just returned the URL of the image to the HTML page and set the src attribute of <img> tag with the returned URL.

    app.py:

    from flask import Flask, render_template
    
    app = Flask(__name__)
    
    
    @app.route("/")
    def hello():
        return render_template('a.html')
    
    @app.route("/getimage")
    def get_img():
        return "a.jpg"
    
    
    if __name__ == '__main__':
        app.run()
    

    a.html:

    <html>
      <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
      </head>
       <body>
         <button type='button' id ='retrieve'>Submit</button>
         <img src="" id="myimg" />
       </body>
      <script>
        $(document).ready(function() {
           $('#retrieve').click(function(){
               $.ajax({
               url: "{{ url_for ('get_img') }}",
               type: "GET",
               success: function(response) {
                   $("#myimg").attr('src', '/static/' + response);
              },
              error: function(xhr) {
                //Do Something to handle error
             }
             });
           });
        });
      </script>
    </html>
    

    You can modify this code as you wish.

    Note: The a.html file should be in templates folder and the a.jpg file should be in the static folder.

    Hope this helps. Good luck.