如何将base64写入模型's文件字段

How to write base64 to model's FileField?

本文关键字:文件 字段 模型 base64      更新时间:2023-09-26

在客户端上,我通过.readAsDataURL(f)函数将文件转换为base64,并通过套接字以json形式发送。在服务器端,我使用以下代码:

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

当我发送.txt文件时一切正常,但当我以这种方式上传图像时,打开后我会收到"图像已损坏"的消息。我哪里错了?

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

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