Force File Download

Posted by gabriel, Wed May 21 10:25:00 UTC 2008

One handy feature that browser’s offer is the ability to automatically open know file types in their respective program. There are however times when you want to force the user to download the file, you want the Save As dialog box to appear to the user.

In order to avoid the default behavior and stop file from being open automatically you can use the content-disposition header. This is an HTTP header, and is not asp.net specific.

Content-disposition: attachment; filename=fname.ext

To do this using asp.net resources you can use the Response object to set the header like this:

Response.AppendHeader(“Content-disposition”, “attachment; filename=” + fileName);

It’s very simple and very handy. I wrote a working example below:


<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Button1_Click(object sender, EventArgs e)
    {
        string fileName = "MyFile.doc";
        string filePath = Server.MapPath("MyFiles/"+fileName);
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.ContentType = "Application/msword";
        Response.WriteFile(filePath);
        Response.End();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Download" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>


Filed Under: Tips and Tutorials | Tags: asp.net

Comments