django return file over HttpResonse - file is not served correctly
Posted
by Tom Tom
on Stack Overflow
See other posts from Stack Overflow
or by Tom Tom
Published on 2010-03-29T13:52:31Z
Indexed on
2010/03/29
14:03 UTC
Read the original article
Hit count: 448
django
|filestream
I want to return some files in a HttpResponse and I'm using the following function. The file that is returned always has a filesize of 1kb and I do not know why. I can open the file, but it seems that it is not served correctly. Thus I wanted to know how one can return files with django/python over a HttpResponse.
@login_required
def serve_upload_files(request, file_url):
import os.path
import mimetypes
mimetypes.init()
try:
file_path = settings.UPLOAD_LOCATION + '/' + file_url
fsock = open(file_path,"r")
#fsock = open(file_path,"r").read()
file_name = os.path.basename(file_path)
mime_type_guess = mimetypes.guess_type(file_name)
try:
if mime_type_guess is not None:
response = HttpResponse(mimetype=mime_type_guess[0])
response['Content-Disposition'] = 'attachment; filename=' + file_name
response.write(fsock)
finally:
fsock.close()
except IOError:
response = HttpResponseNotFound()
return response
© Stack Overflow or respective owner