【问题标题】:Creating a downloadable Link with pk in Django在 Django 中使用 pk 创建可下载链接
【发布时间】:2020-07-11 16:20:28
【问题描述】:

我希望能够点击触发下载的按钮,为了更好地理解,我的代码如下

    import mimetypes

    From wsgiref.util import Filewrapper

    def audio_download (request, pk):
        download =get_object_or_404(Audio,pk=pk)

        file =download.audio.audio.url.strip('/')
        wrapper = FileWrapper(open(file, 'rb'))
        response= HttpResponse(wrapper, content_type='application/force-download')
        response ['Content-Disposition]="attachment; filename="+os.path.basename(file)
        Print ('response')
        return response

然后是我的网址:

  url (r'^audio/download/(P<pk>\d+)/$, views.audio_download, name= 'audio_download')

最后,HTML

    {%for audio in audio%}
    <a href = "audio/download/{{audio.id}}">{{audio.title}}</a></center>
    {%endfor%}

【问题讨论】:

  • 我认为您的问题已经得到解答,例如:stackoverflow.com/a/36394206/2047157
  • 在函数audio_download 内使用ipdb 之类的调试器来检查发生了什么。
  • 很可能不相关,但您不应硬编码您的网址(也不应使用相对网址路径 FWIW)-use the {% url %} templatetag instead
  • @darkless,谢谢,但是没有使用 pk(主键),file_path 在代码中的真正含义是什么......谢谢
  • @darkless 非常感谢,PDF、doc 等文件与您分享给我的参考链接可以正常工作,但 mp4 视频等文件似乎无法下载.. 请帮助

标签: python django twitter-bootstrap url view


【解决方案1】:

我认为不是HttpResponse

response= HttpResponse(wrapper, content_type='application/force-download')

你可以试试FileResponse:

from django.http import FileResponse

response= FileResponse(open(file, 'rb'), content_type='application/force-download')
response ['Content-Disposition]="attachment; filename="+os.path.basename(file)

【讨论】:

    【解决方案2】:

    我的问题得到了答案,我觉得我应该与有类似问题的其他用户分享

    import mimetypes
    From wsgiref.util import Filewrapper
    
    
    def audio_download (request, path):
        audio_path =os.path.join(settings.MEDIA_ROOT, path)
    if os.path.exists(file_path):
        with open(file_path, 'rb') as fh:
        response= HttpResponse(fh.read(), content_type='application/mp3')
        response ['Content-Disposition]="inline; filename="+os.path.basename(file_path)
        Print ('response')
        return response
    raise Http404
    

    我的模板和 URL 的其余部分保持不变

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多