从Django下载的docx文件已损坏

时间:2018-02-10 13:26:18

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

我试图从表单中获取用户输入,然后使用该数据使用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})

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

您必须在io的回复中阅读getvalue(),因为您正在将文档写入io

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

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