从django 1.4.3中的媒体下载文件

时间:2013-03-06 07:59:52

标签: python django file download media

我正在使用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 url访问主页时,file_form.html页面将显示一个包含带上传选项的文件的表单,因此当我们上传文件时正在成功上传并重定向到files_list.html页面,该页面显示媒体目录中上传文件的列表以及下载该特定文件的URL。

最后,当我们点击表格形式的每个文件旁边的链接时,我的目的是下载上传的文件,如files_list.html页面所示。​​

当我们点击链接时,我搜索了很多关于下载特定上传文件的内容,但是无法找到它,所以请点赞。

任何人都可以告诉我如何通过实现files_list.html页面中显示的锚标记概念来从媒体下载文件

如果有人用我的download视图函数填充下载该特定文件的代码会更有帮助,这样我几乎可以非常快地学习它......

被修改

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

url.py

将以下行添加到url conf

     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 :(得分: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