diff --git a/app.py b/app.py index 127eb3b04fae7772763fdeecd668ae3e019c79c3..ae2ab5aa278892115575973dbb0cc9b5034bb405 100644 --- a/app.py +++ b/app.py @@ -5,17 +5,19 @@ from flask import Flask, render_template, request app = Flask(__name__) +UPLOAD_FOLDER ='./static/images' def read_messages_from_file(): """ Read all messages from a JSON file""" with open('data.json') as messages_file: return json.load(messages_file) -def append_message_to_file(content): +def append_message_to_file(img_path, content): """ Read the contents of JSON file, add this message to it's contents, then write it back to disk. """ data = read_messages_from_file() new_message = { 'content': content, + 'img_path': img_path, 'timestamp': datetime.now().isoformat(" ", "seconds") } @@ -29,10 +31,14 @@ def append_message_to_file(content): # The Flask route, defining the main behaviour of the webserver: @app.route("/handle_message", methods=['POST']) def handleMessage(): + img_path = "" new_message = request.form['msg'] - + if('file' in request.files and request.files['file']): + image = request.files['file'] + img_path = os.path.join(UPLOAD_FOLDER, image.filename) + image.save(img_path) if new_message: - append_message_to_file(new_message) + append_message_to_file(img_path, new_message) return render_template('handle_message.html', message=new_message) diff --git a/templates/home.html b/templates/home.html index 3f16144e92ad3071cec6543aa5f4a38cb63658a1..fc6505a5dda57e884981148df697a87b5de28da3 100644 --- a/templates/home.html +++ b/templates/home.html @@ -3,22 +3,23 @@ https://jinja.palletsprojects.com/en/3.0.x/ --> <title>Message board</title> <body> - <h4>Welcome to Message board </h4> + <h4>Welcome to Pelle's Message board </h4> There are {{ messages|length }} messages on the board. </ br> <h4> Here are the last 10:</h4> <ul> {% for m in messages[-9:]|reverse %} - <li> - "{{m.content}}" <small>Posted on {{m.timestamp}} </small> - </li> + <li> + "{{m.content}}" <small>Posted on {{m.timestamp}} </small> <img src="{{ m.img_path }}" width="500"> + </li> {% endfor %} </ul> <h4> Enter a new message</h4> - <form action="/handle_message" method="post" > + <form action="/handle_message" method="post" enctype=multipart/form-data > <label >Your message:</label><br> <input type="text" name="msg"><br> + <input type="file" name="file"><br> <input type="submit" value="Submit"> </form> </body>