Having Django serve downloadable files

后端 未结 15 1578
野的像风
野的像风 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: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 =)

提交回复
热议问题