25

What is the best way to implement, from a web page a download action using asp.net 2.0?

Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.

Community
  • 1
  • 1
HadleyHope
  • 1,173
  • 1
  • 10
  • 19

2 Answers2

38

Does this help:

http://www.west-wind.com/weblog/posts/76293.aspx

Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt");
Response.TransmitFile( Server.MapPath("~/logfile.txt") );
Response.End();

Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.

Martin
  • 39,569
  • 20
  • 99
  • 130
  • 9
    A KEY part of this is the Response.End() - without it you will end up with occasionally corrupt downloads, broken digital signatures, all sorts of weirdness. – Jason Short Apr 21 '09 at 04:54
  • Can this be used or modified to grab a remote file from another URL ? – AlexVPerl Jun 17 '15 at 19:43
12

http://forums.asp.net/p/1481083/3457332.aspx

string filename = @"Specify the file path in the server over here....";
FileInfo fileInfo = new FileInfo(filename);

if (fileInfo.Exists)
{
   Response.Clear();
   Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
   Response.AddHeader("Content-Length", fileInfo.Length.ToString());
   Response.ContentType = "application/octet-stream";
   Response.Flush();
   Response.TransmitFile(fileInfo.FullName);
   Response.End();
}


Update:

The initial code

Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInfo.Name);

has "inline;attachment" i.e. two values for Content Disposition.

Don't know when exactly it started, but in Firefox only the proper file name was not appearing. The file download box appears with the name of the webpage and its extension (pagename.aspx). After download, if you rename it back to the actual name; file opens successfully.

As per this page, it operates on First Come First Served basis. Changing the value to attachment only solved the issue.

PS: I am not sure if this is the best practice but the issue is resolved.

BiLaL
  • 708
  • 11
  • 18
  • 3
    -1: As Martin said, use TransmitFile instead of WriteFile. WriteFile is essentially broken for large files – Niki Jun 05 '10 at 19:43
  • I'm doing just this with a button inside of a ModalPopupExtender operating an update panel and it won't work. However, if I move the button outside of the modalpopup/updatepanel area it works flawlessly? Any ideas how to get around this? – JoeManiaci Feb 16 '16 at 18:10