【问题标题】:Download the files from media in django 1.4.3从 django 1.4.3 中的媒体下载文件
【发布时间】:2013-03-06 07:59:52
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: python django file download media


    【解决方案1】:
    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
    

    【讨论】:

    • :我们如何从锚标签中的模板 files_list.html 发送文件名和路径到文件?
    • k 我尝试了同样的方法,文件正在下载,但是当我打开它时,文件中没有任何内容并显示一些错误
    • 如何匹配 url 中的模式?我尝试了类似 url(r'^download/.*)$', 'learn_django.views.download'),然后出现了以下错误
    • 异常值:不平衡括号异常位置:/usr/lib64/python2.7/re.py in _compile, line 245
    • 那么如何将url中的文件名与re模式匹配呢?
    猜你喜欢
    • 1970-01-01
    • 2016-09-02
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多