Controlling browser behavior for S3 Objects in ASP.NET


In ASP.NET, you can force the browser to view a file on a separate page by setting the appropriate headers in the Response object.

Below are examples for ASP.NET showing how to force a file download.

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

The code sample below demonstrates retrieving a PDF file and writing it directly to the browser response. This approach can be applied to any supported toolkit and file type.

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.