[Django]-How to download a file uploaded using django-filebrowser?

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

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.

Leave a comment