Tuesday, April 14, 2009

How to upload file to user with ASP.NET

Following code snippet allows to write file to http responce stream thus allowing users to download files dynamically created by your web application. 


var filename = @"C:\temp\Report.xls";
Page.Response.ContentType = "application/vnd.ms-excel";
Page.Response.AddHeader("Content-Disposition", 
"attachment; filename= Report.xls");
            
byte[] bytes = File.ReadAllBytes(filename);
Page.Response.OutputStream.Write(bytes, 0, bytes.Length);
Page.Response.OutputStream.Flush();
Page.Response.End();

Note that filename in Page.Responce.AddHeader can be changed to the one you want user to see when his/her download window popups.

No comments:

Post a Comment