fix embedded file upload

This commit is contained in:
j3d1 2023-11-20 20:09:58 +01:00
parent aa0bb9fd0d
commit 27589a09bd
4 changed files with 76 additions and 19 deletions

View file

@ -14,11 +14,19 @@ class FileManager(models.Manager):
if 'data' in kwargs and type(kwargs['data']) == str:
import base64
from hashlib import sha256
content = base64.b64decode(kwargs['data'], validate=True)
raw = kwargs['data']
if not raw.startswith('data:'):
raise ValueError('data must be a base64 encoded string or file and hash must be provided')
raw = raw.split(';base64,')
if len(raw) != 2:
raise ValueError('data must be a base64 encoded string or file and hash must be provided')
mime_type = raw[0].split(':')[1]
content = base64.b64decode(raw[1], validate=True)
kwargs.pop('data')
content_hash = sha256(content).hexdigest()
kwargs['file'] = ContentFile(content, content_hash)
kwargs['hash'] = content_hash
kwargs['mime_type'] = mime_type
else:
raise ValueError('data must be a base64 encoded string or file and hash must be provided')
try:
@ -30,11 +38,19 @@ class FileManager(models.Manager):
if 'data' in kwargs and type(kwargs['data']) == str:
import base64
from hashlib import sha256
content = base64.b64decode(kwargs['data'], validate=True)
raw = kwargs['data']
if not raw.startswith('data:'):
raise ValueError('data must be a base64 encoded string or file and hash must be provided')
raw = raw.split(';base64,')
if len(raw) != 2:
raise ValueError('data must be a base64 encoded string or file and hash must be provided')
mime_type = raw[0].split(':')[1]
content = base64.b64decode(raw[1], validate=True)
kwargs.pop('data')
content_hash = sha256(content).hexdigest()
kwargs['file'] = ContentFile(content, content_hash)
kwargs['hash'] = content_hash
kwargs['mime_type'] = mime_type
elif 'file' in kwargs and 'hash' in kwargs and type(kwargs['file']) == ContentFile:
pass
else: