使用 Django 下载文件

Tes*_*man 2 python django

这可能是一个简单的问题,但我不知何故无法找到解决方案。Django 提供了很多关于上传文件的内容,但我该如何下载文件。

假设我们在 HTML 上有一个按钮uploads/something.txt作为文件。

我尝试过django.views.static.serve,但是这样做会在网页上打开一个文件。

我的问题很简单:我们网站的用户下载文件的最佳和最 Python 的方式是什么?

mas*_*nun 6

  • 您需要阅读该文件。
  • 将其HttpResponse与适当的内容类型一起使用。

这是一些示例代码:

content = open("uploads/something.txt").read()
return HttpResponse(content, content_type='text/plain')
Run Code Online (Sandbox Code Playgroud)

这应该提供一个文本文件。

但是正如您所描述的,在某些浏览器上,它不会要求下载文件,而是会在浏览器中显示它。如果要显示下载提示,请使用以下命令:

response = HttpResponse(open("uploads/something.txt", 'rb').read())
response['Content-Type'] = 'text/plain'
response['Content-Disposition'] = 'attachment; filename=DownloadedText.txt'
return response
Run Code Online (Sandbox Code Playgroud)

但是,请注意,通过 nginx 或您选择的反向代理提供静态内容或上传的文件可能是一个更好的主意。通过 Django 发送大文件可能不是这样做的最佳方式。