Serving Downloadable Files with Django
Users on a website often require the ability to download files, but securing the files and preventing direct downloads is crucial. One solution is to obscure the file paths so that users cannot access them directly.
To achieve this, create a URL that includes a parameter, such as:
http://example.com/download/?f=somefile.txt
Suppose the downloadable files reside in the folder /home/user/files/. Django can be configured to serve the files for download without requiring a specific URL and View to display the file.
The X-Sendfile module offers an optimal solution. It allows Django to locate the file and specify its headers, while the actual file serving is handled by the web server (e.g., Apache, Lighttpd). After installing and configuring mod_xsendfile, integrate it with your view:
from django.utils.encoding import smart_str response = HttpResponse(content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) response['X-Sendfile'] = smart_str(path_to_file) return response
Note that this approach requires server control or a hosting company that supports mod_xsendfile.
Additional Considerations:
The above is the detailed content of How Can Django Securely Serve Downloadable Files Using X-Sendfile (or X-Accel-Redirect)?. For more information, please follow other related articles on the PHP Chinese website!