首页 > 解决方案 > 我们如何在 django 中将上传的 docx 文件转换为 pdf

问题描述

我创建了一个接受文件的模型。我正在尝试将上传的 docx 文件转换为 pdf 并将其显示给用户。为了将 docx 文件转换为 pdf,我正在尝试使用 python 的 docxtopdf 模块。但是当我将文件传递request.FILES['Doc]给转换函数时,它会给出错误:

TypeError at /convview/
expected str, bytes or os.PathLike object, not FieldFile

这是来自views.py文件的代码:

    def post(self, request, *args, **kwargs):
    form = self.get_form()
    if form.is_valid():
        pdffile=UserConvert(Doc=request.FILES['Doc'])
        pdffile.save()
        convert(pdffile.Doc)

当文件在内存中时,我们如何更改文件的 MIME 类型?

标签: pythondjangodjango-modelsfile-conversionfilefield

解决方案


您正在将 a 传递FieldFile给函数,但需要一个 str、字节或路径:

TypeError expected str, bytes or os.PathLike object, not FieldFile

您需要使用path参数获取文件的路径:

convert(pdffile.Doc.path)

推荐阅读