How can I generating file to download with Django

0 votes
Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?
Aug 7, 2020 in Python by kartik
• 37,520 points
5,402 views

1 answer to this question.

0 votes

Hello @kartik,

To trigger a download you need to set Content-Disposition header:

from django.http import HttpResponse
from wsgiref.util import FileWrapper

# generate the file
response = HttpResponse(FileWrapper(myfile.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=myfile.zip'
return response

If you don't want the file on disk you need to use StringIO

import cStringIO as StringIO

myfile = StringIO.StringIO()
while not_finished:
    # generate chunk
    myfile.write(chunk)

Optionally you can set Content-Length header as well:

response['Content-Length'] = myfile.tell()

Hope it helps!!

Thank You!!

answered Aug 7, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

I want to download a file from the website by web scraping. Can anyone explain how to do this in jupyter lab (python) with an example?

Hey, Web scraping is a technique to automatically ...READ MORE

answered Apr 7, 2020 in Python by Gitika
• 65,890 points
2,327 views
0 votes
1 answer

How can I write nested dictionaries to a csv file?

You can use the pandas library to ...READ MORE

answered Apr 17, 2018 in Python by anonymous
1,108 views
0 votes
0 answers
0 votes
1 answer

How can I get the absolute URL (with domain) in Django?

Hello @kartik, Use handy request.build_absolute_uri() method on request, pass it ...READ MORE

answered Aug 6, 2020 in Python by Niroj
• 82,880 points
10,223 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,322 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,478 views
0 votes
1 answer

How can I enable project_id parameter of DJango to be optional?

Hello @kartik, There are several approaches. One is to ...READ MORE

answered Jul 3, 2020 in Python by Niroj
• 82,880 points
884 views
0 votes
1 answer

How can I render HTML to PDF in Django site?

Hello @kartik, Use this code to generate the PDF ...READ MORE

answered Jul 29, 2020 in Python by Niroj
• 82,880 points
4,442 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP