Django 提供下载文件 [英] Django Serving a Download File

查看:30
本文介绍了Django 提供下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提供一个由一些内容生成的 txt 文件,但我遇到了一些问题.我已经创建了临时文件并使用 NamedTemporaryFile 编写了内容,然后将 delete 设置为 false 进行调试,但下载的文件不包含任何内容.

I'm trying to serve a txt file generated with some content and i am having some issues. I'vecreated the temp files and written the content using NamedTemporaryFile and just set delete to false to debug however the downloaded file does not contain anything.

我的猜测是响应值没有指向正确的文件,因此没有下载任何东西,这是我的代码:

My guess is the response values are not pointed to the correct file, hense nothing is being downloaded, heres my code:

    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 :

Have you considered just sending p.body through the response like this:

response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)

这篇关于Django 提供下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆