[Fixed]-Django Serving a Download File

21👍

Have you considered just sending p.body through the response like this:

response = HttpResponse(mimetype='text/plain')
response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid
response.write(p.body)
👤Ric

3👍

XSend requires the path to the file in
response['X-Sendfile']
So, you can do

response['X-Sendfile'] = smart_str(path_to_file)

Here, path_to_file is the full path to the file (not just the name of the file)
Checkout this django-snippet

1👍

There can be several problems with your approach:

  • file content does not have to be flushed, add f.flush() as mentioned in comment above
  • NamedTemporaryFile is deleted on closing, what might happen just as you exit your function, so the webserver has no chance to pick it up
  • temporary file name might be out of paths which web server is configured to send using X-Sendfile

Maybe it would be better to use StreamingHttpResponse instead of creating temporary files and X-Sendfile

1👍

import urllib2;   
url ="http://chart.apis.google.com/chart?cht=qr&chs=300x300&chl=s&chld=H|0"; 
opener = urllib2.urlopen(url);  
mimetype = "application/octet-stream"
response = HttpResponse(opener.read(), mimetype=mimetype)
response["Content-Disposition"]= "attachment; filename=aktel.png"
return response 

Leave a comment