I created a small flask website with 2 functions: upload pictures and display it on the website.
The website always saves newly uploaded images in the same name, image.png
, to replace the previously uploaded image. When I upload a new file, it replaces the old file in the static/img
directory successfully. However, the website keeps displaying the old image.
The closest problem I could find on stackoverflow was Overwriting Image with same name - Django. The answer here suggests using signals but didn't explain why this is happening. I'm hoping someone can clarify what I'm doing wrong if possible.
What can I do to make sure the newly uploaded image is displayed?
You can reproduce my situation using below information.
Directory Structure
├── main.py
├── static
│ └── img
│ └── image.png
└── templates
└── index.html
main.py
import os
from flask import Flask, request, redirect, url_for, render_template
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'static/img/'
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
file = request.files['image']
filename = "image.png"
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return render_template('index.html', filename=filename)
else:
return render_template('index.html')
@app.route('/<filename>')
def display_img(filename):
"""Display image on website"""
return redirect(url_for('static', filename='img/' + filename))
if __name__ == "__main__":
app.run(debug=True)
index.html
<!-- Display Image -->
{% if filename %}
<img src="{{ url_for('display_img', filename=filename) }}" alt="alt">
{% endif %}
<!-- Upload Image Button -->
<form action="#", method="POST", enctype=multipart/form-data>
<input type="file" name="image" id="image"/>
<button type="submit" value="Submit">Submit</button>
</form>