2017-04-25 193 views
0

我有一組文件(.pptx文件),我希望將它們提供給用戶下載。我正在使用django來達到這個目的。我有一些地方想出了使用這些鏈接:Django - 提供文件供下載

having-django-serve-downloadable-files

我面臨的問題是在連接這些部件。相關的代碼件 -

settings.py文件

MEDIA_ROOT = PROJECT_DIR.parent.child('media') 
MEDIA_URL = '/media/' 

HTML模板。變量slide_loc有該文件的位置(例如:path/to/file/filename.pptx

<div class = 'project_data slide_loc'> 
<a href = "{{ MEDIA_URL }}{{ slide_loc }}">Download </a> 
</div> 

views.py文件

def doc_dwnldr(request, file_path, original_filename): 
    fp = open(file_path, 'rb') 
    response = HttpResponse(fp.read()) 
    fp.close() 
    type, encoding = mimetypes.guess_type(original_filename) 
    if type is None: 
     type = 'application/octet-stream' 
    response['Content-Type'] = type 
    response['Content-Length'] = str(os.stat(file_path).st_size) 
    if encoding is not None: 
     response['Content-Encoding'] = encoding 

    # To inspect details for the below code, see http://greenbytes.de/tech/tc2231/ 
    if u'WebKit' in request.META['HTTP_USER_AGENT']: 
     # Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly. 
     filename_header = 'filename=%s' % original_filename.encode('utf-8') 
    elif u'MSIE' in request.META['HTTP_USER_AGENT']: 
     # IE does not support internationalized filename at all. 
     # It can only recognize internationalized URL, so we do the trick via routing rules. 
     filename_header = '' 
    else: 
     # For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers). 
     filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(original_filename.encode('utf-8')) 
    response['Content-Disposition'] = 'attachment; ' + filename_header 
    return response 

urls.py文件

if settings.DEBUG: 
    urlpatterns += static(settings.MEDIA_URL, 
          document_root=settings.MEDIA_ROOT) 

,我找的是細節 - 當用戶點擊下載按鈕,我如何映射URL和doc_dwnldr函數views.py文件

回答

1

在你網址,您需要創建類似:

url(r'^(?P<file_path>\w+)/(?P<original_filename>\w+)/$', views.doc_dwnldr, name='doc_dwnldr') 

將映射到被點擊模板的鏈接,當你具備的功能。

模板

然後,這樣做:

<a href="{% url 'doc_dwnldr' file_path='file_path_variable_here', original_filename='filename_variable_here' %}">Download </a>