我希望网站上的用户能够下载路径被遮蔽的文件,这样他们就不能直接下载。

例如,我希望URL是这样的:http://example.com/download/?f=somefile.txt

在服务器上,我知道所有可下载的文件都位于/home/user/files/文件夹中。

有没有一种方法可以让Django为下载提供这个文件,而不是试图找到一个URL和视图来显示它?


当前回答

对于一个非常简单但不是有效或可扩展的解决方案,你可以使用内置的django serve视图。这对于快速原型或一次性工作是非常好的,但正如在这个问题中所提到的,你应该在生产中使用apache或nginx之类的东西。

from django.views.static import serve
filepath = '/some/path/to/local/file.txt'
return serve(request, os.path.basename(filepath), os.path.dirname(filepath))

其他回答

我遇到过同样的问题不止一次,所以使用xsendfile模块和django filelibrary的auth视图装饰器来实现。请随意使用它作为您自己的解决方案的灵感。

https://github.com/danielsokolowski/django-filelibrary

为了“两全皆美”,你可以将s.l ot的解决方案与xsendfile模块结合起来:django生成文件的路径(或文件本身),但实际的文件服务由Apache/Lighttpd处理。一旦你设置了mod_xsendfile,集成你的视图需要几行代码:

from django.utils.encoding import smart_str

response = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
# It's usually a good idea to set the 'Content-Length' header too.
# You can also set any other required headers: Cache-Control, etc.
return response

当然,这只有在你能控制你的服务器,或者你的主机公司已经设置了mod_xsendfile的情况下才会起作用。

编辑:

在django 1.7中,Mimetype被content_type取代

response = HttpResponse(content_type='application/force-download')  

编辑: 对于nginx检查,它使用X-Accel-Redirect而不是apache的X-Sendfile头。

尝试@Rocketmonkeys解决方案,但下载的文件被存储为*.bin,并被随机命名。这当然不好。添加来自@elo80ka的另一行就解决了这个问题。 下面是我现在使用的代码:

from wsgiref.util import FileWrapper
from django.http import HttpResponse

filename = "/home/stackoverflow-addict/private-folder(not-porn)/image.jpg"
wrapper = FileWrapper(file(filename))
response = HttpResponse(wrapper, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename)
response['Content-Length'] = os.path.getsize(filename)
return response

你现在可以把文件存储在一个私有目录中(不是在/media或/public_html中),并通过django将它们暴露给特定的用户或在特定的情况下。 希望能有所帮助。 感谢@elo80ka, @S。Lott和@Rocketmonkeys的答案,得到了完美的解决方案=)

上面提到过,mod_xsendfile方法不允许在文件名中使用非ascii字符。

出于这个原因,我有一个补丁mod_xsendfile,将允许任何文件被发送,只要名称是url编码,和额外的头:

X-SendFile-Encoding: url

也会被发送。

http://ben.timby.com/?p=149

这里只提到Django 1.10中提供的FileResponse对象

编辑:在寻找一种简单的通过Django进行文件流处理的方法时,我遇到了自己的答案,所以这里有一个更完整的例子(给未来的我)。它假设FileField名称为imported_file

views.py

from django.views.generic.detail import DetailView   
from django.http import FileResponse
class BaseFileDownloadView(DetailView):
  def get(self, request, *args, **kwargs):
    filename=self.kwargs.get('filename', None)
    if filename is None:
      raise ValueError("Found empty filename")
    some_file = self.model.objects.get(imported_file=filename)
    response = FileResponse(some_file.imported_file, content_type="text/csv")
    # https://docs.djangoproject.com/en/1.11/howto/outputting-csv/#streaming-large-csv-files
    response['Content-Disposition'] = 'attachment; filename="%s"'%filename
    return response

class SomeFileDownloadView(BaseFileDownloadView):
    model = SomeModel

urls . py

...
url(r'^somefile/(?P<filename>[-\w_\\-\\.]+)$', views.SomeFileDownloadView.as_view(), name='somefile-download'),
...