hmm sorry about the trend that's been happening on my blog lately .. Got caught with lots of work and have loads of things to blog about now .. Keep reading. Ok back to business . Here's something which i faced recently ! Another ASP.NET problem which you will definitely get stuck into pretty soon if you have requirements to download files created on the fly.
Here's what my code looked like to enable a file download on clicking on a button.
string ExportData = "" , Filename = "", ContentType = "";
ExportData = GenerateCSV(p_omyDataSet);
ContentType = "application/octet-stream";
Filename = "CSV View.CSV";
Response.Clear();
Response.ContentType = ContentType ;
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + Filename + "\"") ;
Response.Flush();
Response.Write( ExportData );
Response.End();
Here i generate a CSV file dynamically and then render the same by changing the Content-type for the Response. Well sounds pretty easy doesn't it ! hmm yeah logically this should have worked beautifully without any problem ! But the hang up is that, since the content-type of the response has changed, the browser will think that this page will not be compatible anymore for the current content-type and so will throw an error on any subsequent operations you do on the page.
I had some javascripts on the page which should have worked in the background once the page renders but i was getting an 'Access Denied'
error ! Didnt get the feel of it for a long time until i figured out what was going on in the background ...
I dont know how i got stuck into a situation so very simple and made it complicated but then isn't this all the code that is necessary to get the job done ?? Where am i going wrong ? I searched some newsgroups, googled around for a more elegant solution but then couldn't find any with the time constraints i had.
Implemented a workaround instead to get the job done for now ! Using a hidden IFRAME and then sending a request to download the
content in the IFRAME because of which only the content-type for the IFRAME changes and the page itself works normally. Also it gives the impression of a background operation (async) and the user can work normally on his activities in the foreground until the Download File message box is thrown up with Open and Save options ...
Any better way of doing this ?? If someone has a very elegant solution feel free to post about it here ..