Return zip to download from view in django

I am trying to load a zip file in my Django application.

How do I get it back from view?

I tried the code below, but I get some kind of warning in the browser with the contents of the file inside my zip code.

What am I doing wrong?

def download_logs(request): date = datetime.datetime.now().__str__().replace(" ", "_").split(".")[0] os.system("df -h . > /tmp/disk_space") response = HttpResponse(mimetype='application/zip') response['Content-Disposition'] = 'filename=logs_%s.zip' % date files = [] files.append("/tmp/disk_space") buffer = StringIO() zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) for name in files: file = open(name, "r") zip.writestr(name, file.read()) file.close() zip.close() buffer.flush() ret_zip = buffer.getvalue() buffer.close() response.write(ret_zip) return response 
+4
source share
2 answers

You must tell the browser to treat the response as an attachment.

From docs you should do something like:

 >> response = HttpResponse(my_data, mimetype='application/vnd.ms-excel') >>> response['Content-Disposition'] = 'attachment; filename=foo.xls' 
+2
source

Here is a link to the actual working code for creating a ZipFile in memory and returning it to the user as a download file: django-rosetta view.py

+2
source

All Articles