This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

6 Dec 2012

UPLOADING DOC / DOCX FILES IN ASP.NET

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:

UploadDocFiles1

When a file other than ms word file:

UploadDocFiles2

Download Sample Code here: WordFilesUpload.rar


visit: Difference between .doc and .docx extension files

1 comment:

  1. [...] Previous posts i have explained about  simple example for UPLOADING FILES IN ASP.NET  and  UPLOADING DOC / DOCX FILES IN ASP.NET . Actually the default maximum size of files that can be uploaded in ASP.NET is  4MB ( [...]

    ReplyDelete

Thanks for your comments.
-Sameer