从Django下载的DOCX文件已损坏



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

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

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

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

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

,或者您可以直接写入响应,如@paleolimbot指出的那样。

最新更新