【问题标题】:Django - Serve files for downloadDjango - 提供文件以供下载
【发布时间】:2017-09-22 11:15:57
【问题描述】:

我有一组文档(.pptx 文件),我希望将其提供给用户下载。我为此目的使用 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)

我正在寻找的细节是 - 当用户点击下载按钮时,我如何在 views.py 文件中映射 url 和 doc_dwnldr 函数

【问题讨论】:

    标签: python django


    【解决方案1】:

    在您的 urls 中,您需要创建如下内容:

    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>
    

    【讨论】:

      猜你喜欢
      • 2017-10-09
      • 1970-01-01
      • 2013-03-25
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多