Having Django serve downloadable files

后端 未结 15 1566
野的像风
野的像风 2020-11-22 05:46

I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.

For instance, I\'d like the URL to be something

相关标签:
15条回答
  • 2020-11-22 06:46

    I have faced the same problem more then once and so implemented using xsendfile module and auth view decorators the django-filelibrary. Feel free to use it as inspiration for your own solution.

    https://github.com/danielsokolowski/django-filelibrary

    0 讨论(0)
  • 2020-11-22 06:50

    For a very simple but not efficient or scalable solution, you can just use the built in django serve view. This is excellent for quick prototypes or one-off work, but as has been mentioned throughout this question, you should use something like apache or nginx in production.

    from django.views.static import serve
    filepath = '/some/path/to/local/file.txt'
    return serve(request, os.path.basename(filepath), os.path.dirname(filepath))
    
    0 讨论(0)
  • 2020-11-22 06:51

    Tried @Rocketmonkeys solution but downloaded files were being stored as *.bin and given random names. That's not fine of course. Adding another line from @elo80ka solved the problem.
    Here is the code I'm using now:

    from wsgiref.util import FileWrapper
    from django.http import HttpResponse
    
    filename = "/home/stackoverflow-addict/private-folder(not-porn)/image.jpg"
    wrapper = FileWrapper(file(filename))
    response = HttpResponse(wrapper, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename)
    response['Content-Length'] = os.path.getsize(filename)
    return response
    

    You can now store files in a private directory (not inside /media nor /public_html) and expose them via django to certain users or under certain circumstances.
    Hope it helps.

    Thanks to @elo80ka, @S.Lott and @Rocketmonkeys for the answers, got the perfect solution combining all of them =)

    0 讨论(0)
提交回复
热议问题