我的Django模型中有filefield:
I have filefield in my django model:
file=models.FileField(verbose_name=u'附件',upload_to='attachment/%Y/%m/%d',max_length=480)此文件将显示在网页中,链接为"test/home/projects/89/attachment/2012/02/24/sscsx.txt"
This file will display in the web page with link "test/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文档的以下部分: docs.djangoproject/en/dev/ref/request-response/#telling-the-browser-to-treat将响应作为文件附件
See the following part of the Django documentation on sending files directly: docs.djangoproject/en/dev/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment
更多推荐
如何在Django视图中下载文件字段文件
发布评论