Skip to content

Commit

Permalink
Add feature: remove images (#21)
Browse files Browse the repository at this point in the history
* Save PNGs as JPEGs so they don’t break

* Convert RGBA images to RGB with white background (fix #15)

* Add dummy image deletion button if current user uploaded the image

* Add image deletion JS prompt

* Implement image deletion prompt with form validation

* Add functional image deletion route (fix #1)
  • Loading branch information
felixbade committed Aug 2, 2021
1 parent 9a02468 commit 04ea07a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
29 changes: 27 additions & 2 deletions app/controllers/image_uploads.py
@@ -1,12 +1,13 @@
from random import random
from os import path
import os
from uuid import uuid4

from flask import render_template, request, redirect, url_for, send_from_directory, abort
import PIL.Image

from app import app, db
from app.models.image import Image
from app.controllers.user import get_user

def random_filename():
return str(uuid4())
Expand Down Expand Up @@ -57,14 +58,38 @@ def save_uploaded_image(file, user):
filename = random_filename() + extension
db.session.add(Image(filename=filename, user_id=user.id))
db.session.commit()
save_path = path.join(app.config['UPLOAD_FOLDER'], filename)
save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
with open(save_path, 'w') as f:
image.save(f, image_format)

return True



# Image deletion
@app.route('/delete-image', methods=['POST'])
def delete_image():
user = get_user()
image_id = request.form.get('image-id')
image = Image.query.filter_by(id=image_id).first()
if not image:
abort(404)
if user != image.user:
abort(403)

image_path = os.path.join(app.config['UPLOAD_FOLDER'], image.filename)
try:
os.remove(image_path)
except FileNotFoundError:
pass

db.session.delete(image)
db.session.commit()

return redirect(url_for('view_frontpage'))



# This is similar to how Nginx would serve the static images if we
# want to do that at some point.

Expand Down
15 changes: 15 additions & 0 deletions app/templates/image_info.html
Expand Up @@ -7,4 +7,19 @@
User: <a href="{{ url_for('profile', username=image.user.username) }}">{{ image.user.username }}</a>
<img class="fullwidth" src="{{ image.url }}">

{% if image.user == get_user() %}
<script>
let checkDeletion = (event) => {
let answer = prompt("Are you sure you want to delete this image? This action cannot be undone. Please type \"delete\" to confirm.")
if (answer !== 'delete') {
event.preventDefault()
}
}
</script>
<form action="/delete-image" method="post" onsubmit="return checkDeletion(event)">
<input type="hidden" name="image-id" value="{{ image.id }}">
<button name="delete-button" value="true">Delete this image</button>
</form>
{% endif %}

{% endblock %}

0 comments on commit 04ea07a

Please sign in to comment.