Question

I need to download a file from a server and to get a pop-up 'save as' box on the client. I can't do this in Ajax, so I create a hidden form in the client JavaScript, and I submit the form in the JS when a button is clicked. The server gets a POST, and it sends the file back as an attachment, and the client produces the 'save' box.

So far, so good, except that there are two problems here:

1 - I want the JS to delete the newly-created form when the user has completed the download. I suppose I could just leave a useless hidden form in the DOM, but it's not ideal. The problem is that form.submit() executes asynchronously, so I don't know when to delete the form - I can't simply do it after executing form.submit()

2 - Sometimes the user actually needs to download two files. This code doesn't work:

form1.submit();   // download file 1
form2.submit();   // download file 2

The client only executes/completes one of the submits - I can do both by putting an alert between the two, for example, but I need to do it properly.

If I was doing this with Ajax, I'd just make the calls synchronous, but I can't find a way to do this with form submission. Ideally I'd like an attribute to make the submit synchronous (something like .setAttribute('async', false), which doesn't work).

Any ideas? Or another way to download two files with two save-as dialogs?

Was it helpful?

Solution

A great trick is to use a cookie. The trick works like this:

  1. Create your temporary form, and add two extra fields that you populate, one with a cookie name and the other with some unique value (could be random, could be a timestamp or a counter; doesn't really matter).
  2. Submit the form.
  3. At the server, the code should do whatever it normally does to create the download. It should also create a new cookie with the given name and value. Return the response.
  4. Back at the client, right after submitting the form, start an interval timer to check (every 100ms or so) to see if there's a cookie with the chosen name and chosen unique value. As soon as you see the cookie, you know that the form response has arrived!

As to downloading two files, I don't think there are any provisions in HTTP for two attachments. You can of course return something like a zip file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top