4

I am trying to create a download of a file object. the file was added using django-filebrowser which means it is turn in to a string path to the the file. I have tried the following:

f = Obj.objects.get(id=obj_id)
myfile = FileObject(os.path.join(MEDIA_ROOT, f.Audio.path))
...

response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'

return response

The file that is downloaded contains the string of the path to the file location and not the file. Could anyone be of assistance on how to access the file object?

1

2 Answers 2

1
f = Obj.objects.get(id=obj_id)
myfile = open(os.path.join(MEDIA_ROOT, f.Audio.path)).read()
...

response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'

return response

NOTE! This is not memory friendly! Since the whole file is put into memory. You're better of using a webserver for file serving or if you want to use Django for file serving you could use xsendfile or have a look at this thread

Sign up to request clarification or add additional context in comments.

Comments

0

You need to open the file and send it's binary contents back in the response. So something like:

fileObject = FileObject(os.path.join(MEDIA_ROOT, f.Audio.path))
myfile = open(fileObject.path)
response = HttpResponse(myfile.read(), mimetype="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'
return response

Hope that gets what you're looking for.

3 Comments

FileObject is from django-filebrowser ´from filebrowser.base import FileObject´
Thanks @ejey, I updated my example to hopefully match what you'd need to do. Also, William's response is something to consider, if this is a large file it's going to take up a lot of memory space.
I've just tested and encountered problems right away. I'm trying to use chunks() if that fails I will have a look at Willian's suggestions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.