Click here to Skip to main content
14,028,549 members
Click here to Skip to main content
Add your own
alternative version

Stats

3K views
1 bookmarked
Posted 11 Oct 2013
Licenced CPOL

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

, 11 Oct 2013
Rate this:
Please Sign up or sign in to vote.
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:
<a href="http://www.iana.org/assignments/media-types/application/index.html">http://www.iana.org/assignments/media-types/application/index.html</a>
Happy coding
Tonny

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ASP.NET Community
United States United States
The ASP.NET Wiki was started by Scott Hanselman in February of 2008. The idea is that folks spend a lot of time trolling the blogs, googlinglive-searching for answers to common "How To" questions. There's piles of fantastic community-created and MSFT-created content out there, but if it's not found by a search engine and the right combination of keywords, it's often lost.

The ASP.NET Wiki articles moved to CodeProject in October 2013 and will live on, loved, protected and updated by the community.
Group type: Collaborative Group

760 members


You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190419.4 | Last Updated 11 Oct 2013
Article Copyright 2013 by ASP.NET Community
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid