Home > Article > Backend Development > How to Securely Serve Downloadable Files in Django Without Exposing Direct File Paths?
Question:
How can Django serve downloadable files securely while concealing their direct download paths?
Answer:
Django does not directly support serving downloadable files. To implement this functionality, consider the following approach:
Using the xsendfile Module
Pros:
Implementation:
from django.utils.encoding import smart_str from django.http import HttpResponse def download_view(request): file_path = '/home/user/files/somefile.txt' file_name = 'somefile.txt' response = HttpResponse(content_type='application/force-download') response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name) response['X-Sendfile'] = smart_str(file_path) return response
Note: This approach requires mod_xsendfile to be enabled on your server.
Conclusion:
By utilizing the xsendfile module, you can securely serve downloadable files in Django while preventing direct access to their original locations. This approach offers both security and flexibility in handling file downloads.
The above is the detailed content of How to Securely Serve Downloadable Files in Django Without Exposing Direct File Paths?. For more information, please follow other related articles on the PHP Chinese website!