Allowed uploading of other kind of images than jpg/png

This commit is contained in:
2025-05-04 19:33:42 +02:00
parent e661162ad2
commit 1209dfdd87

View File

@@ -1,4 +1,7 @@
import hashlib import hashlib
import random
import string
from io import BytesIO
from PIL import Image as PILImage from PIL import Image as PILImage
from PIL import JpegImagePlugin from PIL import JpegImagePlugin
@@ -33,8 +36,7 @@ def upload(request):
bucket = get_b2_resource() bucket = get_b2_resource()
file_md5_hash = hashlib.file_digest(file, "md5").hexdigest() filename = file.name
file.seek(0)
with PILImage.open(file) as im: with PILImage.open(file) as im:
height, width = (im.height, im.width) height, width = (im.height, im.width)
@@ -46,19 +48,32 @@ def upload(request):
file_extension = "png" file_extension = "png"
content_type = "image/png" content_type = "image/png"
else: else:
return JsonResponse( new_file = BytesIO()
{"created": False, "error": "Uploaded file should be JPEG or PNG"}, filename = (
status=400, "".join(random.choices(string.ascii_uppercase + string.digits, k=12))
+ ".jpg"
) )
im.save(
new_file,
format="jpeg",
quality=95,
icc_profile=im.info.get("icc_profile"),
keep_rgb=True,
)
file = new_file
content_type = "image/jpeg"
file_extension = "jpg"
file.seek(0) file.seek(0)
file_md5_hash = hashlib.file_digest(file, "md5").hexdigest()
file.seek(0)
same_md5_image = Image.objects.filter(original_md5=file_md5_hash).first() same_md5_image = Image.objects.filter(original_md5=file_md5_hash).first()
if same_md5_image: if same_md5_image:
return JsonResponse({"created": False, "id": same_md5_image.id}) return JsonResponse({"created": False, "id": same_md5_image.id})
image = Image( image = Image(
original_name=file.name, original_name=filename,
original_mime_type=content_type, original_mime_type=content_type,
original_md5=file_md5_hash, original_md5=file_md5_hash,
height=height, height=height,