1

I am trying to serve a download file in my django app, after a bit of research I made the code below but there is one problem, the file is opened in the browser instead of being downloaded.

The files that I serve on my app are exe, and when they open it's just a bunch of random characters.

So how can I specify that I want the file to be downloaded, not opened? Thank you

with open(path_to_apk, 'rb') as fh:
     response = HttpResponse(fh)
     response['Content-Disposition'] = 'inline; filename=' + os.path.basename(path_to_apk)
     return response`
Dhia
  • 10,119
  • 11
  • 58
  • 69
  • Possible duplicate of [Generating file to download with Django](http://stackoverflow.com/questions/908258/generating-file-to-download-with-django) – Dhia May 10 '17 at 12:47

3 Answers3

2

You want to set the Content-disposition header to "attachment" (and set the proper content-type too - from the var names I assume those files are android packages, else replace with the proper content type):

response = HttpResponse(fh, content_type="application/vnd.android.package-archive") 
response["Content-disposition"] = "attachment; filename={}".format(os.path.basename(path_to_apk))
return response
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Thanks this seems to be working, there is a misspelling on the code: instead of format you wrote fomat, maybe you can correct it for others who might want to use your solution. – Abderrahman Gourragui May 10 '17 at 12:15
0

First of all you have to set the Content_Disposition header to attachment.

And instead of worrying about correct value for Content_Type header, use FileResponse instead of HttpResponse:

file=open(path_to_apk,"rb")
response=FileResponse(file)
response['Content-Disposition'] = 'attachment; filename={}'.format(os.path.basename(path_to_apk))
return response
Prateek Gupta
  • 2,422
  • 2
  • 16
  • 30
0

You can use a FileResponse with as_attachment=True for this. It will handle stuff like reading the file into memory, setting the correct Content-Type, Content-Disposition, etc. automatically for you.

from django.http import FileResponse

def download_file(request):
    return FileResponse(open(path_to_apk, 'rb'), as_attachment=True)
F30
  • 1,036
  • 1
  • 10
  • 21