Last active
January 24, 2022 22:37
-
-
Save MhmdRyhn/820e3277c157098655dd3ae117be4285 to your computer and use it in GitHub Desktop.
A "django" class based view to "download file" from server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
How to use this view ? | |
---------------------- | |
class YourFileDownloadView(FileDownloadView): | |
folder_path = 'path of the folder where the file is' | |
file_name = 'name of the file to be downloaded' | |
content_type_value = 'content type used for the format of `file_name`' | |
""" | |
from django.conf import settings | |
from django.http import Http404, HttpResponse | |
class FileDownloadView(View): | |
# Set FILE_STORAGE_PATH value in settings.py | |
folder_path = settings.FILE_STORAGE_PATH | |
# Here set the name of the file with extension | |
file_name = '' | |
# Set the content type value | |
content_type_value = 'text/plain' | |
def get(self, request, file_name): | |
self.file_name = file_name | |
file_path = os.path.join(self.folder_path, self.file_name) | |
if os.path.exists(file_path): | |
with open(file_path, 'rb') as fh: | |
response = HttpResponse( | |
fh.read(), | |
content_type=self.content_type_value | |
) | |
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) | |
return response | |
else: | |
raise Http404 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍