Download a file with Javascript via POST

Viewed 1232

I currently use this solution to download excel files via javascript. When a user clicks a button, my javascript creates a url which I load with an iframe. This solution works for short urls. However, I've come across a case where my url is too long for a get request. I'd like to preserve the same behavior such that no new windows open for the excel export. However, I'd be OK with opening a temporary window if necessary. I've thought of one solution which I'd like to avoid:

  1. Make a POST request that creates the excel file, saves it to a temp folder, and returns the unique file name.
  2. Request the file name in a url constructed for the iframe.

I don't like this solution because it requires a non trivial amount of work to setup a temp folder that will be shared across all of our web servers. Also, I simply would rather not create a temporary file if I don't need to.

current code:

$("body").append('<iframe width="0" height="0" frameborder="0" src="' + dynamicallyCreatedUrl + '"></iframe>');

Is there a way I can make a POST request to download an excel file via javascript?

This solution must work for IE8+, Firefox, Chrome. Just for reference: I'm using IIS7, ASP.Net MVC, C#. I have access to YUI and JQuery.

1 Answers

I know this doesn't help with downloading files in POST, but it provides an alternative solution to your problem without changing much.

I suggest that you use a URL shortener API. Basically, you can just pass them a long URL and have them give you a shortened version of the URL.

Here are the first two i thought of:

tinyurl doesn't seem to allow cross domain javascript, so you need your server to make the GET request to them and return the URL to your client.

bitly allows cross domain javascript, but it looks like you might need to add some authentication

Related