我正在尝试提供一个由某些内容生成的 txt 文件,但我遇到了一些问题。我已经创建了临时文件并使用 NamedTemporaryFile 编写了内容,只是将 delete 设置为 false 进行调试,但下载的文件不包含任何内容。
我的猜测是响应值没有指向正确的文件,所以没有下载任何东西,这是我的代码:
f = NamedTemporaryFile()
f.write(p.body)
response = HttpResponse(FileWrapper(f), mimetype='application/force-download')
response['Content-Disposition'] = 'attachment; filename=test-%s.txt' % p.uuid
response['X-Sendfile'] = f.name
最佳答案
您是否考虑过像这样通过 response
发送 p.body
:
response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)
关于python - Django 提供下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15790136/