3

I need to download files, which is triggered via AJAX. My code retrieves images from URLs in a temp folder, and creates an in memory zip of the the files in this temp folder. I want to push the file path to the client. How would I do it?

Here is my zipping code:

#This function creates a temp folder, downloads images in it and returns the path
temp_dir = retrieve_images(file_paths)

in_memory_loc = io.BytesIO()

zipf = zipfile.ZipFile(, 'w')
zipdir(temp_dir, zipf)
zipf.close()

#remove the temp directory
shutil.rmtree(temp_dir)

in_memory_loc.seek(0)

#output the zip file to the browser
return send_file(in_memory_loc, attachment_filename='site_images.zip', as_attachment=False)

This works when I use the traditional form submit way. But I need to return this over AJAX. Returning a file over AJAX seems impossible, hence I want to return the zip file path. How would I do it?

Nikaido
  • 4,443
  • 5
  • 30
  • 47
Rutwick Gangurde
  • 4,772
  • 11
  • 53
  • 87
  • I might consider removing the code and the Python tag from this question, because as far as I can tell it's a general web question that has nothing to do with Python or zip files. – Chris Martin Apr 12 '16 at 07:22
  • Yes but the language I am using is Python. And people generally tend to find answers for the language they are coding in! – Rutwick Gangurde Apr 12 '16 at 07:28

3 Answers3

2

Create a url to that resource and send it back to the ajax, trigger the download with window.open('url'); in the success function

You have the name of the temp directory and the name of the file you have all that you need to build a url

madalinivascu
  • 32,064
  • 4
  • 39
  • 55
1

You can't prompt a file download with an XHR response, so the server will have to hold onto the content of the zip file and wait for the client to make a second HTTP request to perform the download.

One approach would be to store the content in memcache under a randomly-generated key, and return the key with the XHR response. Then the client can pass that key back to the server in a non-XHR request to request the file.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
  • How would I create a URL to the in memory location? Or, how would I tell zipfile to store that zip in the same temp location? Apologies, I am a newbie. – Rutwick Gangurde Apr 12 '16 at 07:15
0

(without ajax)
You can use window location within Jquery click function for download zip file ......

 $(this).ready(function() {
        $("#downloadBtn").click(function() {
            var formdata= $("#formId").serialize();
            window.location="download.action?"+formdata;
        });
    });