Wednesday, January 26, 2011

How to download a file using AJAX

I struggled for half of my day finding this.

Actually in our project, there is a CART. The requirement is when we click on downloadCart button, it should download the contents of the cart and clear the cart as well.

The first issue that I faced was...

As the response has a zip file to be downloaded, hence in our Action class, they were writing bytes to the response, and in the end, when they return SUCCESS, (I forgot to tell u, we are using struts in our project) it gives an exception : java.lang.illegalStateException, that is expected.

So, what's the solution...

After discussing this with my friend Sukhbir, he suggested that we can't return any view after we have committed the response. But how to handle this scenario.

He suggested, make 2 calls, using javascript, and put it on onClick event of the button.
One for downloading, and the second one for re-loading the cart (So that it gets refreshed).

I did the code for downloading using AJAX.... $.get and $.ajax
But the issue now came up was....

Ajax calls work in background and it doesn't lets the user see that something has downloaded......no response, no prompt.......nothing........

Now what??

Then I came to know that there are APIs available in jquery for handling binary data when data is coming from server. I googled this also a lot, but, couldn't find anything that worked for me.

I found a very pretty and simple solution on internet now...Here it is...
Thanks to Eric for this help

Source : Google Group Forums Link

Final Solution
function test(url){ 
  var elemIF = document.createElement("iframe"); 
  elemIF.src = url; 
  elemIF.style.display = "none"; 
  document.body.appendChild(elemIF); 
} 



Related posts : http://particletree.com/notebook/ajax-file-download-or-not/

No comments:

Post a Comment