Downloading the files(which are uploaded) from media folder in django 1.4.3

后端 未结 5 2066
悲&欢浪女
悲&欢浪女 2020-12-16 02:17

I am using django to design the basic web pages that handles the uploading and downloading of the files to/from the media folder

相关标签:
5条回答
  • 2020-12-16 02:58

    Just remove / after filename.

    Change this:

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

    to this:

    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) 
    
    0 讨论(0)
  • 2020-12-16 03:05

    Your code is right but there is one redundant character in 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
    

    At last line the filename attribute has a trailing slash (/): filename=%s/

    Which causes the problem. Remove this slash and it works.

    0 讨论(0)
  • 2020-12-16 03:07

    These are all not required.In HTML you can download the media file by using <a download="{video.URL}">

    For example:

    <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>
    
    0 讨论(0)
  • 2020-12-16 03:13
    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
    
    0 讨论(0)
  • 2020-12-16 03:20

    I solved the problem by replacing

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

    with

    response['Content-Disposition'] = 'attachment; filename="diploma_{}{}"'.format(str(someID),'.pdf')
    
    0 讨论(0)
提交回复
热议问题