如何在 Django 视图中下载文件字段文件 [英] how to download a filefield file in django view
问题描述
我的 Django 模型中有文件字段:
I have filefield in my django model:
file=models.FileField(verbose_name=u'附件',upload_to='attachment/%Y/%m/%d',max_length=480)
该文件将显示在带有链接http://test.com.cn/home/projects/89/attachment/2012/02/24/sscsx.txt"的网页中
This file will display in the web page with link "http://test.com.cn/home/projects/89/attachment/2012/02/24/sscsx.txt"
我想要做的是当用户点击文件链接时,它会自动下载文件;谁能告诉我如何在视图中执行此操作?
What I want to do is when user click the file link, it will download the file automatically; Can anyone tell me how to do this in the view?
提前致谢!
推荐答案
你可以试试下面的代码,假设 object_name
是那个模型的对象:
You can try the following code, assuming that object_name
is an object of that model:
filename = object_name.file.name.split('/')[-1]
response = HttpResponse(object_name.file, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
有关直接发送文件的内容,请参阅 Django 文档的以下部分:https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-响应作为文件附件
See the following part of the Django documentation on sending files directly: https://docs.djangoproject.com/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment
这篇关于如何在 Django 视图中下载文件字段文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!