Having Django serve downloadable files

后端 未结 15 1825
野的像风
野的像风 2020-11-22 05:46

I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.

For instance, I\'d like the URL to be something

15条回答
  •  滥情空心
    2020-11-22 06:44

    Just mentioning the FileResponse object available in Django 1.10

    Edit: Just ran into my own answer while searching for an easy way to stream files via Django, so here is a more complete example (to future me). It assumes that the FileField name is 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[-\w_\\-\\.]+)$', views.SomeFileDownloadView.as_view(), name='somefile-download'),
    ...
    

提交回复
热议问题