在Django 1.4.3中下载媒体文件

0 投票
1 回答
3883 浏览
提问于 2025-04-17 18:06

我正在使用Django设计两个基本页面,一个页面用于上传文件到媒体库,另一个页面列出所有上传的文件,并提供下载这些文件的链接。下面是我的代码:

url.py

from django.conf.urls.defaults import *
from django.conf import settings

urlpatterns = patterns('',
             url(r'^files$', 'learn_django.views.upload_file'),
             url(r'^list_of_files$', 'learn_django.views.files_list'),
             url(r'^download$', 'learn_django.views.download'),
)
if settings.DEBUG:
    urlpatterns = patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
) + urlpatterns

views.py

from django.conf import settings
from django.shortcuts import render_to_response
from learn_django.forms import UploadFileForm
import os

def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid() and form.is_multipart():
            handle_uploaded_file(request.FILES['file'])
            return HttpResponseRedirect('/files_list')
    else:
        form = UploadFileForm()
    return render_to_response('files_form.html', {'form': form},context_instance=RequestContext(request))

def handle_uploaded_file(file,path=''):
    filename = file._get_name()
    destination_file = open('%s/%s' % (settings.MEDIA_ROOT, str(path) + str(filename)), 'wb+')
    for chunk in file.chunks():
        destination_file.write(chunk)
    destination_file.close()

def files_list(request):
    return render_to_response('files_list.html',{'total_files':os.listdir(settings.MEDIA_ROOT),'path':settings.MEDIA_ROOT},context_instance=RequestContext(request))

def download(request):
    #do something to downlaod the files here.....
    return something

files_list.html

<table border="1" colspan="2" width="100%">
   <tr>
     <th width="60%">File</td>
     <th width="40%">Download</td> 
   </tr>
 {% for file in total_files %}
   <tr>
     <td width="60%">{{file}}</td>
     <td width="40%" align="center"><a href="/download" style="text-decoration:None">Download here</a></td> 
   </tr>
 {% endfor %}  
</table>

在上面的代码中,当我们访问 files 这个网址时,会显示 file_form.html 页面,上面有一个表单可以上传文件。当我们上传文件时,它会成功上传,并重定向到 files_list.html 页面,这个页面会显示在媒体目录中上传的文件列表,并提供下载这些文件的链接。

我的最终目的是,当我们点击每个文件旁边的链接时,可以下载该文件,正如在 files_list.html 页面中以表格形式展示的那样。

我在网上搜索了很多关于如何在点击链接时下载特定上传文件的信息,但没有找到,所以我来这里询问。

有没有人能告诉我如何通过在 files_list.html 页面中使用锚标签的方式来下载媒体中的文件?

如果有人能帮我完善我的 download 视图函数,提供下载特定文件的代码,那将对我学习非常有帮助……

编辑

编辑后,我更新了我的代码如下:

url.py

在网址配置中添加了以下行:

     url(r'^download/(?P<file_name>.+)$', 'learn_django.views.download'),

编辑后的下载视图函数如下:

def download(request,file_name):
    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
    response['X-Sendfile'] = smart_str(settings.MEDIA_ROOT + file_name)
    return response

HTML文件中的锚标签如下:

<td width="40%" align="center"><a href="/download/{{file}}" style="text-decoration:None">Download here</a></td>

所以当我点击 download 链接时,出现了以下错误:

Request Method: GET
Request URL:    http://localhost:8000/download
Django Version: 1.4.3
Exception Type: error
Exception Value:    
unbalanced parenthesis
Exception Location: /usr/lib64/python2.7/re.py in _compile, line 245
Python Executable:  /usr/bin/python

1 个回答

0
url(r'^download/$', 'learn_django.views.download'),

<a href="/download/?file_name={{file}}">Download</a>

def download(request):
    file_name = request.GET.get('per_page')
    path_to_file = "/media/{0}".format(file_name)
    response = HttpResponse(mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
    response['X-Sendfile'] = smart_str(path_to_file)
    return response

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

撰写回答