如何将base64写入模型的FileField?

How to write base64 to model's FileField?

在客户端上,我通过 .readAsDataURL(f) 函数将文件转换为 base64,然后通过套接字将其发送到 json。 在服务器端我使用这个代码:

AttachedFile.objects.create(file=ContentFile(b64decode(b64string), filename))

当我发送 .txt 文件时一切正常,但是当我通过这种方式上传图片时,打开后我收到 "Image is corrupted" 消息。我哪里错了?

您需要使用 base64.split('base64,') 的第二部分:

AttachedFile.objects.create(message=cm, file=ContentFile(b64decode(value.split('base64,')[1]), key))