Save server memory with Response.TransmitFile()

So, two common tasks that I encounter when sending files to the browser:

  1. Open file within the browser
  2. Open "file download" dialog box

I used to use the Response.Write() method, but recently came across the Response.TransmitFile() method. This method directly writes the file to the HTTP response stream without saving the file to memory on the server, thus saving server memory (especially for big files).

1) Open file within the browser: The following code will preface the response object as a PDF file, and then transmit the file directly to the HTTP response.  Then, it will flush the response to the browser, and stops execution of the page.  Typically, the behavior that this evokes is Adobe Reader will open inside the browser and download the document so that the user can view its contents within Adobe Reader.

Response.ContentType = "application/pdf";
//write file to the buffer
Response.TransmitFile(@"e:\inet\www\docs\testdoc.pdf");
Response.End();

2) Open "file download" dialog box: If you do not want the PDF to automatically open inside the browser window, you can give the user the "File Download" option.  This dialog box typically lets the user either open, save, or cancel the file.  The method for communicating this behavior to the browser is to add an http header "content-disposition" to the response object. 

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=testdoc.pdf");
Response.TransmitFile(@"e:\inet\www\docs\testdoc.pdf");
Response.End();
 
This is the 'File Download' box that pops up using the second method

 

9 Comments

Comments have been disabled for this content.