Having Django serve downloadable files

后端 未结 15 1568
野的像风
野的像风 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:37

    For the "best of both worlds" you could combine S.Lott's solution with the xsendfile module: django generates the path to the file (or the file itself), but the actual file serving is handled by Apache/Lighttpd. Once you've set up mod_xsendfile, integrating with your view takes a few lines of code:

    from django.utils.encoding import smart_str
    
    response = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
    response['X-Sendfile'] = smart_str(path_to_file)
    # It's usually a good idea to set the 'Content-Length' header too.
    # You can also set any other required headers: Cache-Control, etc.
    return response
    

    Of course, this will only work if you have control over your server, or your hosting company has mod_xsendfile already set up.

    EDIT:

    mimetype is replaced by content_type for django 1.7

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

    EDIT: For nginx check this, it uses X-Accel-Redirect instead of apache X-Sendfile header.

提交回复
热议问题