如何在Django视图中下载文件字段文件

编程入门 行业动态 更新时间:2024-10-24 20:22:31
本文介绍了如何在Django视图中下载文件字段文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的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视图中下载文件字段文件

本文发布于:2023-11-26 07:09:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633130.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   字段   视图   如何在   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!