16

I have interesting task which requires me to download a dynamically generated file from a server (ASP.NET) to the client. On the client side it is just JavaScript (jQuery) and the client is able to generate a lot of parameters to customize how the data is exported.

What is the best way to do download the file from the server? Should I use a WCF service such as what is described here or simple page like this one?

I don't know how to download a file without reloading the page (I'm not sure that $.ajax will work in this case). Could someone please give me some direction on this topic? Thanks.

Steve
  • 7,747
  • 5
  • 31
  • 44
Arbejdsglæde
  • 13,670
  • 26
  • 78
  • 144
  • 2
    I think this is related to this question/answer: http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – Ali Almahdi Jun 06 '12 at 10:41

1 Answers1

20

First you can create the file from a handler .ashx

Let say that you have the file for downloading at download.ashx and you have some parametres to pass from your javascript, eg download.ashx?p1=8827&p2=8831 to know what you going to create.

Then on your javascript you simple can make a redirect as

window.location = "download.ashx?p1=8827&p2=8831";

or alternative you can use the window.open for do the same think

window.open("download.ashx?p1=8827&p2=8831");

and your file will start the download.

Just make sure that you have set the header of attachment, and the correct contenttype on your handle eg:

  HttpContext.Current.Response.ContentType = "application/octet-stream";
  HttpContext.Current.Response.AddHeader("Content-Disposition", 
                    "attachment; filename=" + SaveAsThisFileName);

Simple and clear, both tested and working.

Also you may interesting on this answer: How to handle errors.

Community
  • 1
  • 1
Aristos
  • 66,005
  • 16
  • 114
  • 150
  • How do you do error handling? For instance, how would you handle an exception being thrown in the .ashx file? – Steve Jan 30 '13 at 15:46
  • 1
    @Steve If you have an error you throw the page not found, log the error and fix it. – Aristos Jan 30 '13 at 16:13
  • @BogdanM. You short it down, send an id, not some full url. This is a different issue to solve/handle, that you can not avoid - but is not that hard. – Aristos Jan 08 '14 at 10:05
  • I was just wondering if the suggested solution remains the best. Most modern browsers have enabled pop-up blockers. So the redirection that is proposed here as the accepted method I think is not the rightest solution. I face the same problem so I would appreciate if anyone could give his/her feedback. – gkoul Mar 25 '17 at 19:50
  • @GrigoriosKoulouras the `window.location` is not pop-up anything and starts the download. – Aristos Mar 25 '17 at 22:10