13

I'm trying to serve a txt file generated with some content and i am having some issues. I'vecreated the temp files and written the content using NamedTemporaryFile and just set delete to false to debug however the downloaded file does not contain anything.

My guess is the response values are not pointed to the correct file, hense nothing is being downloaded, heres my code:

    f = NamedTemporaryFile()
    f.write(p.body)

    response = HttpResponse(FileWrapper(f), mimetype='application/force-download')
    response['Content-Disposition'] = 'attachment; filename=test-%s.txt' % p.uuid
    response['X-Sendfile'] = f.name
Callum
  • 1,136
  • 3
  • 17
  • 43

4 Answers4

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
  • 8,615
  • 3
  • 17
  • 21
  • 1
    In Django 1.9 it should be response = HttpResponse(p.body, content_type='text/plain'); response['Content-Disposition'] = 'attachment; filename="%s.txt"' % p.uuid – Makers_F Dec 15 '15 at 07:23
  • This is the correct answer for the question as it is text content that is served. A lot of people who want to serve binary files are also landing here. Answers by @Saurabh Chandra Patel is good for serving binary files – Mohammed Shareef C Jun 21 '20 at 12:13
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

karthikr
  • 97,368
  • 26
  • 197
  • 188
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...

Michal Čihař
  • 9,799
  • 6
  • 49
  • 87
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 
Saurabh Chandra Patel
  • 12,712
  • 6
  • 88
  • 78