【问题标题】:Downloading the files(which are uploaded) from media folder in django 1.4.3从 django 1.4.3 中的媒体文件夹下载文件(已上传)
【发布时间】:2013-03-06 11:53:40
【问题描述】:

我正在使用 django 来设计处理 uploadingdownloading 的文件到/来自 media 文件夹的基本网页

实际上文件已成功上传到媒体文件夹,文件也已成功下载,但last charaterlast charater 一样将underscore 附加到文件名后,例如file_one.pdf_file_two.pdf_file_three.txt_ 等,

下面是我的代码

urls.py

urlpatterns = patterns('',
             url(r'^upload$', 'learn_django.views.upload'),
             url(r'^files_list$', 'learn_django.views.files_list'),
             url(r'^download/(?P<file_name>.+)$', '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

def upload(request):
    ......
    ....
    return render_to_response('uploads_form.html', {'form': form},context_instance=RequestContext(request))


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,file_name):
    file_path = settings.MEDIA_ROOT +'/'+ file_name
    file_wrapper = FileWrapper(file(file_path,'rb'))
    file_mimetype = mimetypes.guess_type(file_path)
    response = HttpResponse(file_wrapper, content_type=file_mimetype )
    response['X-Sendfile'] = file_path
    response['Content-Length'] = os.stat(file_path).st_size
    response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(file_name) 
    return response

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/{{file}}" style="text-decoration:None">Download here</a></td>
   </tr>
 {% endfor %}  
</table>

所以在上面的代码中,当一个文件成功上传到媒体时,它会被重定向到files_list.htmlfiles_list查看函数,它以表格的形式显示文件总数,旁边有一个下载链接到每个文件名。

因此,当我们点击下载锚链接时,将通过执行函数download 下载相应的文件。

所以文件下载成功,但underscore _ 附加到文件名的最后一个,如file_one.pdf_file_two.pdf_file_three.txt_ 等。

那么谁能告诉我,我上面的下载功能代码有什么问题,为什么underscore会附加到file name,以及如何从文件名中删除underscore...

【问题讨论】:

    标签: python django file download media


    【解决方案1】:

    您的代码是正确的,但download 中有一个冗余字符:

    def download(request,file_name):
        file_path = settings.MEDIA_ROOT +'/'+ file_name
        file_wrapper = FileWrapper(file(file_path,'rb'))
        file_mimetype = mimetypes.guess_type(file_path)
        response = HttpResponse(file_wrapper, content_type=file_mimetype )
        response['X-Sendfile'] = file_path
        response['Content-Length'] = os.stat(file_path).st_size
        response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(file_name) 
        return response
    

    文件名属性的最后一行有一个斜杠 (/):filename=%s/

    导致问题的原因。去掉这个斜线就可以了。

    【讨论】:

      【解决方案2】:

      只需删除文件名后的/

      改变这个:

      response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(file_name) 
      

      到这里:

      response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) 
      

      【讨论】:

        【解决方案3】:

        这些都不是必需的。在 HTML 中,您可以使用 &lt;a download="{video.URL}"&gt; 下载媒体文件

        例如:

        <button class="btn btn-outline-info">
        <a href="{{result.products.full_video.url}}" download="{{result.products.full_video.url}}" style="text-decoration:None" class="footer_link">Download<i class="fa fa-download"></i></a>
        </button>
        

        【讨论】:

          【解决方案4】:

          我通过替换解决了问题

          response['Content-Disposition'] = 'attachment; filename=diploma_"' + str(someID) + '.pdf"'
          

          response['Content-Disposition'] = 'attachment; filename="diploma_{}{}"'.format(str(someID),'.pdf')
          

          【讨论】:

            【解决方案5】:
            import urllib, mimetypes
            from django.http import HttpResponse, Http404, StreamingHttpResponse, FileResponse
            import os
            from django.conf import settings
            from wsgiref.util import FileWrapper
            
            class DownloadFileView(django_views):
                def get(self,request,file_name):
                    file_path = settings.MEDIA_ROOT +'/'+ file_name
                    file_wrapper = FileWrapper(open(file_path,'rb'))
                    file_mimetype = mimetypes.guess_type(file_path)
                    response = HttpResponse(file_wrapper, content_type=file_mimetype )
                    response['X-Sendfile'] = file_path
                    response['Content-Length'] = os.stat(file_path).st_size
                    response['Content-Disposition'] = 'attachment; filename=%s/' % str(file_name) 
                    return response
            

            【讨论】:

            • 欢迎来到 Stack Overflow!仅代码的答案并不是特别有用。请简要说明此代码如何解决问题。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-15
            • 1970-01-01
            • 2018-12-09
            相关资源
            最近更新 更多