【问题标题】:docx file downloaded from Django is corrupt从 Django 下载的 docx 文件已损坏
【发布时间】:2018-02-10 13:26:18
【问题描述】:

我试图从表单中获取用户输入,然后使用该数据使用 python docx 模块创建文档。但是下载的文件没有在 MS Word 中打开。它说文件已损坏。有人可以帮我弄这个吗?

def resume_form(request):
form = forms.resume()

if request.method == 'POST':
    form = forms.resume(request.POST)
    if form.is_valid():
        document = Document()
        document.add_heading(str(form.cleaned_data['full_name']),0)
        document.add_heading('Summary', 1)
        document.add_paragraph(str(form.cleaned_data['summary']))

        f = io.BytesIO()
        document.save(f)
        length = f.tell()
        f.seek(0)
        response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
        response['Content-Disposition'] = 'attachment; filename=download.docx'
        response['Content-Length'] = length
        #document.save(response)
        return response

return render(request, 'sample_app/index.html', {'form' : form})

【问题讨论】:

  • 您正在损坏此行中的文件 检查此行中的正确扩展名 document 。 response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
  • 我从这个网站尝试了 .doc:blogs.msdn.microsoft.com/vsofficedeveloper/2008/05/08/… 它仍然损坏
  • 看看这个链接能不能帮到你stackoverflow.com/questions/19400089/…
  • if form.is_valid(): document = Document() document.add_heading(str(form.cleaned_data['full_name']),0) document.add_heading('Summary', 1) document.add_paragraph(str(form.cleaned_data['summary'])) response = HttpResponse(document, content_type='application/vnd.ms-word') response['Content-Disposition'] = 'attachment; filename=download.docx' document.save(response) return response
  • 我尝试更改扩展名和其他一些更改。但它仍然无法正常工作。我在记事本中打开文件,它看起来像这样:‰–ÄaLÎ^ÓØ« ƒrálv®ZOâèÞ[1Û¶

标签: python django python-3.x django-views python-requests


【解决方案1】:

我认为您的代码中已经有了答案:您可以(并且应该)将文档直接写入响应,而不是使用中介 BytesIO。

...
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename = "download.docx"'
document.save(response)
return response

【讨论】:

  • 谢谢 :) 我试图解决我忘记实际打开(强制)word 文件的“损坏文件”的警告标志。你能告诉我为什么会出现提示/标志吗?
  • 你的意思是提示下载文件?我认为这是一个内容处置/附件的事情,但我是新手,所以不确定是否有办法禁用它(特别是对于 word 文档)。
【解决方案2】:

您必须在使用getvalue() 的响应中读取io,因为您正在将文档写入io。

response = HttpResponse(f.getvalue(), content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')

或者你可以直接写信给@paleolimbot 指出的回复。

【讨论】:

  • 谢谢,我忘记更改那部分了。
猜你喜欢
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 2019-06-22
  • 1970-01-01
  • 2015-09-07
相关资源
最近更新 更多