Django + Postgres:将带有 NUL (0x00) 字符的 PDF 文件保存到 DB 并将其解码回 PDF

Django + Postgres: saving PDF file with NUL (0x00) characters to DB and decoding it back to PDF

我有一个 pdf 文件要保存在我的 Postgres 数据库中

当我尝试保存它带来的文件时 A string literal cannot contain NUL (0x00) characters. 所以我遵循了 here 的解决方案,它用 � 字符

替换了 null unicode(ppbData[0], errors='ignore').replace("\x00", "\uFFFD")

问题是我现在无法将其转换回 PDF。我尝试了 encode() 和其他方法

file = open('new.pdf', 'wb')
file.write(text.encode())
file.close()

但是它 returns 空白 pdf



有什么方法可以用 null 替换 � 字符或任何其他方法将其转换回正常的 pdf 吗?也许第一个替换的解决方案也不对,还有另一种方法吗?

Django 模型 class 有一个 FileField,它在数据库中存储文件名。 https://docs.djangoproject.com/en/3.2/topics/files/#using-files-in-models

实际文件内容通过 settings.DEFAULT_FILE_STORAGE 存储,通常在文件系统中。 https://docs.djangoproject.com/en/3.2/topics/files/#file-storage

不过也可以使用云存储:

如果你真的想将文件存储在数据库中,你可以对其进行base64编码(如Ross Rogers mentioned) or you can use a BinaryField