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?

Ernest Jumbe
  • 758
  • 9
  • 21
  • [Having Django serve downloadable files](http://stackoverflow.com/q/1156246/4279) – jfs Aug 07 '12 at 12:32

2 Answers2

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

Community
  • 1
  • 1
Willian
  • 2,385
  • 15
  • 17
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.

themanatuf
  • 2,880
  • 2
  • 25
  • 39
  • FileObject is from django-filebrowser ´from filebrowser.base import FileObject´ – Ernest Jumbe Aug 07 '12 at 12:06
  • 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. – themanatuf Aug 07 '12 at 12:20
  • 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. – Ernest Jumbe Aug 07 '12 at 12:27