From 3b2a4153f14c76b085eea9ed4da0b3272a92fd98 Mon Sep 17 00:00:00 2001 From: Mitch Riedstra Date: Mon, 23 Oct 2017 12:40:44 -0400 Subject: Name files properly on download --- app/dispatch/views.py | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) (limited to 'app/dispatch/views.py') diff --git a/app/dispatch/views.py b/app/dispatch/views.py index 05a8c2c..4a8a18b 100644 --- a/app/dispatch/views.py +++ b/app/dispatch/views.py @@ -1,5 +1,6 @@ from django.shortcuts import render, redirect -# from django.http import HttpResponse +from django.http import HttpResponse +from django.utils.encoding import smart_str # from django.template import loader from django.core.urlresolvers import reverse # import django.contrib.auth as auth @@ -17,6 +18,7 @@ from django.contrib.auth.mixins import UserPassesTestMixin from datetime import datetime, timedelta from django.utils import formats from dateutil import rrule +import re, os def home(request): return redirect(reverse('load_list')) @@ -272,3 +274,29 @@ def PaperworkDelete(request, load_id, pk): print(e) return redirect(reverse('load_detail', kwargs={'pk': load_id})) + +# Specifically for downloading with the filename set to the description of the +# load +def PaperworkDownload(request, load_id, pk): + try: + load = Load.objects.get(pk=load_id) + paperwork = Paperwork.objects.get(pk=pk) + + if os.path.exists(paperwork.document.path): + with open(paperwork.document.path, 'rb') as fh: + try: + exp = re.compile('\.[^.]*$', re.IGNORECASE) + ext = exp.findall(paperwork.document.path) + ext = ext[0] + except Exception as e: + print(e) + ext = '.pdf' + + desc = load.description.replace('"', '') + + response = HttpResponse(fh.read(), content_type='application/force-download') + response['Content-Disposition'] = 'attachment; filename="{}"'.format(smart_str(desc + ext)) + response['X-Sendfile'] = smart_str(paperwork.document.path) + return response + except Exception as e: + print(e) -- cgit v1.2.3