0

I am making a jquery ajax POST request and passing the data to backend python code in Django framework. I need to return the zip file as httpresponse which should be automatically downloaded in browser.

             object_body = request.body.decode('utf-8')
             loaded_json = json.loads(object_body)

             json_obj = ast.literal_eval(str(loaded_json))

             zip_file_path = importexport.download(json_obj,user)
             zip_filename = os.path.basename(zip_file_path)

             with open(zip_file_path, 'rb') as zip:
               response = HttpResponse(zip.read(), content_type = 'application/x-zip')
               response['Content-Disposition'] = 'attachment; filename=' + zip_filename

             return response
d3514514
  • 71
  • 1
  • 2
  • 8
  • Great question, what does your code result into so far? Do you get an error or do you not get an attachment? – Chuk Ultima Jul 18 '18 at 06:25
  • 1
    Currently what you've got? Any response? any output? – JPG Jul 18 '18 at 06:32
  • https://stackoverflow.com/questions/12881294/django-create-a-zip-of-multiple-files-and-make-it-downloadable check it, – Mr Singh Jul 18 '18 at 06:33
  • The file is not getting downloaded as attachement. In Response, its displaying the zip file contents – d3514514 Jul 18 '18 at 08:43
  • This is the ajax request being passed ....return $.ajax({ url: "/testmgr/importexport/", data: JSON.stringify(data), method: 'POST', dataType: 'application/x-zip', accepts: 'application/x-zip', success: function(response) { }, }); – d3514514 Jul 18 '18 at 08:45

2 Answers2

0

One solution:

put the zip file into MEDIA_ROOT, and redirect to the url of it.

Waket Zheng
  • 5,065
  • 2
  • 17
  • 30
0

If you have download URL (put the file into MEDIA_ROOT), you can just write a tag with download attribute and then click on Download as mentioned in following code snippet, it automatically downloads the file without redirection.

<a href="https://github.com/vaibhavmule/vaibhavmule.github.io/archive/master.zip" download>Download</a>
Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52