Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to enable users to download office documents from your ASP.NET site

0.00/5 (No votes)
18 Mar 2012 1  
A typical request from a customer or user of your website is to enable the upload and download of documents. The could be spreadsheets, presentations

This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.

A typical request from a customer or user of your website is to enable the upload and download of documents. The could be spreadsheets, presentations and word documents. Depending on the setup of your server this can be easy or this can be hard  depending on which mime types the server hosting your website supports.

By default, many web servers are configured to report a MIME type of text/plain or application/octet-stream for unknown content types. As new content types are invented or added to web servers, web administrators may fail to add the new MIME types to their web server's configuration and in not doing that in reality making it impossible for users of your solution to download any file that is of unknown mime type from your website.

Fortunately this can be easily remedied by adding a downloader page to your solution:

Downloader.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DownLoader.aspx.cs" Inherits="usability_DownLoader" EnableEventValidation="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Downloader
    </div>
    </form>
</body>
</html>
Codebehind:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class usability_DownLoader : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["file"] != null)
        {
            string fileId = Request.QueryString["file"].ToString();

            DownloadFile(fileId);
        }
    }

    protected void DownloadFile(string fileId)
    {
        string filePath = QueryFileNameInDB(fileId);      
        string fileName = Path.GetFileName(filePath);

        Response.Clear();
        Response.ContentType = GetMimeType(fileName);
        string encodefileName = HttpUtility.UrlEncode(fileName);
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + encodefileName);
        Response.WriteFile(fileName);
        Response.End();
        Response.Flush();
    }

    protected string GetMimeType(string fileName)
    { 
        string mimeType = "";

        string docType = fileName.LastIndexOf(".");

        int startDocType = docType.LastIndexOf(".");

        docType = docType.Substring(startDocType + 1);

        switch (docType)
        {
            case "doc":
                {
                    mimeType = "application/msword";
                    break;
                }
            case "xls":
                {
                    mimeType = "application/vnd.ms-excel";
                    break;
                }
            case "xlsx":
                {
                    mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    break;
                }
            case "ppt":
                {
                    mimeType = "application/vnd.ms-powerpoint";
                    break;
                }
            case "pptx":
                {
                    mimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
                    break;
                }
            case "docx":
                {
                    mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                    break;
                }
            default:
                {
                    mimeType = "application/pdf";
                    break;
                }
        }

        return mimeType;
    }
}
This solution supports the most commom mime-types and can be easily extended to support other formats.
You can find many of the existing mimetypes here:
http://www.iana.org/assignments/media-types/application/index.html
Happy coding
Tonny

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here