Skip to content

Commit

Permalink
12 - Perform the File Download
Browse files Browse the repository at this point in the history
  • Loading branch information
codingforentrepreneurs committed Nov 9, 2017
1 parent 91cb579 commit 6d92ca1
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 5 deletions.
Binary file modified src/db.sqlite3
Binary file not shown.
3 changes: 3 additions & 0 deletions src/products/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ class ProductFile(models.Model):
def __str__(self):
return str(self.file.name)

def get_default_url(self):
return self.product.get_absolute_url()

def get_download_url(self): # detail view
return reverse("products:download",
kwargs={"slug": self.product.slug, "pk": self.pk}
Expand Down
26 changes: 21 additions & 5 deletions src/products/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import Http404, HttpResponse
from django.views.generic import ListView, DetailView, View
from django.shortcuts import render, get_object_or_404
from django.shortcuts import render, get_object_or_404, redirect

from analytics.mixins import ObjectViewedMixin

Expand Down Expand Up @@ -97,6 +97,12 @@ def get_object(self, *args, **kwargs):
raise Http404("Uhhmmm ")
return instance

import os
from wsgiref.util import FileWrapper # this used in django
from mimetypes import guess_type

from django.conf import settings


class ProductDownloadView(View):
def get(self,*args, **kwargs):
Expand All @@ -107,10 +113,20 @@ def get(self,*args, **kwargs):
raise Http404("Download not found")
download_obj = downloads_qs.first()
# permission checks
# form the download

response = HttpResponse(download_obj.get_download_url())
return response
file_root = settings.PROTECTED_ROOT
filepath = download_obj.file.path # .url /media/
final_filepath = os.path.join(file_root, filepath) # where the file is stored
with open(final_filepath, 'rb') as f:
wrapper = FileWrapper(f)
mimetype = 'application/force-download'
gussed_mimetype = guess_type(filepath)[0] # filename.mp4
if gussed_mimetype:
mimetype = gussed_mimetype
response = HttpResponse(wrapper, content_type=mimetype)
response['Content-Disposition'] = "attachment;filename=%s" %(download_obj.name)
response["X-SendFile"] = str(download_obj.name)
return response
#return redirect(download_obj.get_default_url())



Expand Down
Binary file not shown.

0 comments on commit 6d92ca1

Please sign in to comment.