我希望网站上的用户能够下载路径被遮蔽的文件,这样他们就不能直接下载。
例如,我希望URL是这样的:http://example.com/download/?f=somefile.txt
在服务器上,我知道所有可下载的文件都位于/home/user/files/文件夹中。
有没有一种方法可以让Django为下载提供这个文件,而不是试图找到一个URL和视图来显示它?
我希望网站上的用户能够下载路径被遮蔽的文件,这样他们就不能直接下载。
例如,我希望URL是这样的:http://example.com/download/?f=somefile.txt
在服务器上,我知道所有可下载的文件都位于/home/user/files/文件夹中。
有没有一种方法可以让Django为下载提供这个文件,而不是试图找到一个URL和视图来显示它?
当前回答
我做过一个关于这个的项目。你可以看看我的github回购:
https://github.com/nishant-boro/django-rest-framework-download-expert
这个模块提供了一种使用Apache模块Xsendfile在django rest框架中下载文件的简单方法。它还有一个额外的功能,即只向属于特定群组的用户提供下载服务
其他回答
我遇到过同样的问题不止一次,所以使用xsendfile模块和django filelibrary的auth视图装饰器来实现。请随意使用它作为您自己的解决方案的灵感。
https://github.com/danielsokolowski/django-filelibrary
Django建议您使用另一台服务器来提供静态媒体(在同一台机器上运行另一台服务器是可以的)。他们建议使用lighttp这样的服务器。
设置起来非常简单。然而。如果'somefile.txt'是在请求时生成的(内容是动态的),那么你可能想让django来服务它。
Django Docs -静态文件
我做过一个关于这个的项目。你可以看看我的github回购:
https://github.com/nishant-boro/django-rest-framework-download-expert
这个模块提供了一种使用Apache模块Xsendfile在django rest框架中下载文件的简单方法。它还有一个额外的功能,即只向属于特定群组的用户提供下载服务
这里只提到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'),
...
def qrcodesave(request):
import urllib2;
url ="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=s&chld=H|0";
opener = urllib2.urlopen(url);
content_type = "application/octet-stream"
response = HttpResponse(opener.read(), content_type=content_type)
response["Content-Disposition"]= "attachment; filename=aktel.png"
return response