【问题标题】:Django + Postgres: saving PDF file with NUL (0x00) characters to DB and decoding it back to PDFDjango + Postgres:将带有 NUL (0x00) 字符的 PDF 文件保存到 DB 并将其解码回 PDF
【发布时间】:2021-06-18 14:25:24
【问题描述】:

我有一个 pdf 文件想保存在我的 Postgres DB 中

当我尝试保存文件时,它带来了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()

但它返回空白 pdf



有没有办法用 null 替换 � 字符或任何其他方式将其转换回普通 pdf?也许替换的第一个解决方案也不正确,还有其他方法吗?

【问题讨论】:

  • 问题是\uFFFD 也由有效的二进制字节组成,并且可能已经出现在您的 PDF 中,因此当您将它转换回 over-converts 字节时,您从不编码开始。您可以使用不同的编码——base64.base64.encode(file.read())
  • 稍后使用 base64.b64decode 或 javascript 中的等价物解码。

标签: python django postgresql pdf


【解决方案1】:

Django 模型类有一个 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 所述),也可以使用BinaryField

【讨论】:

    猜你喜欢
    • 2019-12-13
    • 2020-12-20
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多