Reputation: 1083
I'm trying to enable the downloading of previously uploaded files in Django, here's the code I'm using so far:
def downloadview(request):
path=os.path.join('media', 'files', '5560026113', '20180412231515.jpg' )
response = HttpResponse()
response['Content-Type']=''
response['Content-Disposition'] = "attachment; filename='Testname'"
response['X-Sendfile']=smart_str(os.path.join(path))
return response
The inspiration for this trial comes from this thread but I don't get it working. An empty txt file is downloaded instead of the image that is stored on the server. In this trial code the exact filename and extension is hard coded in the path variable.
Upvotes: 1
Views: 3797
Reputation: 6173
Here is a way you can serve a file through Django (although it is usually not a good approach, the better one is to serve files with a webserver like nginx etc - for performance reasons):
from mimetypes import guess_type
from django.http import HttpResponse
file_path=os.path.join('media', 'files', '5560026113', '20180412231515.jpg' )
with open(file_path, 'rb') as f:
response = HttpResponse(f, content_type=guess_type(file_path)[0])
response['Content-Length'] = len(response.content)
return response
guess_type
infers the content_type from the file extension.
https://docs.python.org/3/library/mimetypes.html
more on HttpResponse here: https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpResponse
And here is why it is not recommended to serve files through Django, although not recommended just means that you should probably understand what you are doing: https://docs.djangoproject.com/en/2.0/howto/static-files/deployment/
Upvotes: 4