In previous post we have seen  simple example for uploading files in ASP.NET. And in this post we will see uploading files of particular type. We have to filter the file type based on its Content Type(MIME type). Here I am discussing about uploading doc/docx files in asp.net. Add a new folder “uploads” to your asp website. Because in this example we are uploading files to the Upload folder in our Asp Application. First take a upload control on Default.aspx, the code is give below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <br />
    <br />
    <asp:Label ID="lblMessage" runat="server"></asp:Label>
    <br />
    <br />
    <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click" 
        Text="Submit" />
    </form>
</body>
</html>

The C# code in the code behind file is given below :

using System;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath("." + "\uploads\" + FileUpload1.FileName);

        if (FileUpload1.HasFile)
        {
            lblMessage.Text=FileUpload1.PostedFile.ContentType;
            if (System.IO.File.Exists(path))
            {
                Response.Write("Already exists");
            }
            else
            {
                if (FileUpload1.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || FileUpload1.PostedFile.ContentType=="application/msword")
                {
                    FileUpload1.SaveAs(path);
                    Response.Write("Upload successful");
                }
                else
                {
                    Response.Write("Invalid file format");
                }
            }

        }
        else
        {
            Response.Write("please select file");
        }
    }
}

See the images below:

When a ms word file is uploaded:

upload doc files asp.net

When a file other than ms word file:

Upload doc files Asp.Net

1 thought on “Uploading MS WORD ( DOC / DOCX ) FILES IN ASP.NET”

Leave a Reply

Your email address will not be published. Required fields are marked *