gpt4 book ai didi

python - 从 Django 下载的 docx 文件已损坏

转载 作者:行者123 更新时间:2023-11-30 22:20:58 25 4
gpt4 key购买 nike

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

关于python - 从 Django 下载的 docx 文件已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48721295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com