ASP and ASP.NET - Write data directly to a browser without creating a local copy


Within Classic ASP and ASP.NET you can write data directly a browser without writing it locally
(by setting the LocalFile property). This is done by setting the headers within the Response object.

Below are examples for Classic ASP and ASP.NET of how this can be done to force a download.

By changing the Content-Type from "application/force-download" to "application/pdf", or the name of the file type you wish to use, the content will be displayed in the browser rather than downloaded.

Note that the code samples below use the S3 component of the Amazon Integrator to retrieve a PDF file, but this can be applied to any of the toolkits as well as additional file types.

Classic ASP Dim S31 Set S31 = Server.CreateObject("InAmazon5.S3") S31.AccessKey = "access_key" S31.SecretKey = "secret_key" S31.Bucket = "bucket" S31.GetObject "some_file.pdf" Response.Clear Response.AddHeader "Pragma", "no-cache" ' Content-Type of "application/pdf" will display the PDF in a ' browser if the Content-Disposition header is not added Response.ContentType = "application/force-download" ' Comment the line below out when displaying the PDF in browser Response.AddHeader "Content-Disposition", "attachment; filename=some_file.pdf" Response.AddHeader "Content-Length", UBound(S31.ObjectDataB) Response.AddHeader "Connection", "close" Response.BinaryWrite S31.ObjectDataB

ASP.NET S3 s3 = new S3(); s3.AccessKey = "access_key"; s3.SecretKey = "secret_key"; s3.Bucket = "bucket"; s3.GetObject("some_file.pdf"); HttpContext context = System.Web.HttpContext.Current; context.Response.Clear(); context.Response.AppendHeader("Pragma", "no-cache"); // Content-Type of "application/pdf" will display the PDF in a // browser if the Content-Disposition header is not added context.Response.ContentType = "application/force-download"; // Comment the line below out when displaying the PDF in browser context.Response.AppendHeader("Content-Disposition", "attachment; filename=some_file.pdf"); context.Response.AppendHeader("Content-Length", s3.ObjectDataB.Length.ToString()); context.Response.AppendHeader("Connection", "close"); context.Response.BinaryWrite(s3.ObjectDataB); context.Response.End();

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.