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

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

问题描述

我正在尝试为某个内容生成的txt文件,我有一些问题。我使用NamedTemporaryFile处理临时文件并编写内容,只需将delete设置为false即可进行调试,但下载的文件不包含任何内容。



我的猜测是响应值没有指向正确的文件,hense没有什么是正在下载,还有我的代码:

  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

$ b $您是否考虑过通过响应发送 p.body

code>这样:

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


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

解决方案

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天全站免登陆