Wednesday, 9 October 2013

Word File Upload and Download

UPLOADING AND DOWNLOADING WORD FILES USING ASP.NET



To create this kind of application first you need to create a data base for storing the word files.
STEP-1:- First create a data base and then create a table name it as “WordFiles” which have following fields.


I set the Id column as primary key and auto generate, you can also create as you like. Here name column is for File name, type column is for type of the file and data column is for store the actual content of the file which data type is binary because the contents of the file are stored is bytes.
STEP-2:- Now go to Visual Studio and add a website name it as u like then add a web form name it as “Upload and Download Word Files.aspx” and design the page as like bellow .

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body bgcolor="#996633">
    <form id="form1" runat="server">
    <div align="center">
        <table>
            <tr>
                <td>
                    Select File
                </td>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" ToolTip="Select Only word File" />
                </td>
                <td>
                    <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
                </td>
                <td>
                    <asp:Button ID="Button2" runat="server" Text="View Files" OnClick="Button2_Click" />
                </td>
            </tr>
        </table>
        <table>
            <tr>
                <td>
                    <p>
                        <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
                    </p>
                </td>
            </tr>
        </table>
        <asp:GridView ID="GridView1" runat="server" Caption="All Word Document Files " CaptionAlign="Top"
            HorizontalAlign="Justify" DataKeyNames="id"              OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
            ToolTip="Word FIle DownLoad Tool" CellPadding="4" BackColor="White"                BorderColor="#CC9966"
            BorderStyle="None" BorderWidth="1px">
            <RowStyle BackColor="White" ForeColor="#330099" />
            <Columns>
                <asp:CommandField ShowSelectButton="True" SelectText="Download" ControlStyle-                  ForeColor="Blue">
                    <ControlStyle ForeColor="Red"></ControlStyle>
                </asp:CommandField>
            </Columns>
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <PagerStyle ForeColor="#330099" HorizontalAlign="Center" BackColor="#FFFFCC" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <SortedAscendingCellStyle BackColor="#FEFCEB" />
            <SortedAscendingHeaderStyle BackColor="#AF0101" />
            <SortedDescendingCellStyle BackColor="#F6F0C0" />
            <SortedDescendingHeaderStyle BackColor="#7E0000" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

STEP-3:- Now double click on the Upload button and write the following code.
protected void Button1_Click(object sender, EventArgs e)
    {
        Label2.Visible = true;
        string filePath = FileUpload1.PostedFile.FileName;// getting the file path of uploaded file
        string filename1 = Path.GetFileName(filePath);// getting the file name of uploaded file
        string ext = Path.GetExtension(filename1);// getting the file extension of uploaded file
        string type = String.Empty;

        if (!FileUpload1.HasFile)
        {
            Label2.Text = "Please Select File"; //if file uploader has no file selected
        }
        else
            if (FileUpload1.HasFile)
            {
                try
                {

                    switch (ext) // this switch code validate the files which allow to upload only word file
                    {
                        case ".doc":
                            type = "application/word";
                            break;
                        case ".docx":
                            type = "application/word";
                            break;

                    }

                    if (type != String.Empty)
                    {
                        SqlConnection cn = new SqlConnection("server=AJIT;database=Demo;uid=sa;pwd=123");
                        Stream fs = FileUpload1.PostedFile.InputStream;
                        BinaryReader br = new BinaryReader(fs);  //reads the   binary files
                        Byte[] bytes = br.ReadBytes((Int32)fs.Length);  //counting the file length into bytes
                        cn.Open();
                        SqlCommand com = new SqlCommand("insert into wordFiles (Name,type,data)" + " values (@Name, @type, @Data)", cn); //insert query
                        com.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename1;
                        com.Parameters.Add("@type", SqlDbType.VarChar).Value = type;
                        com.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
                        com.ExecuteNonQuery();
                        Label2.ForeColor = System.Drawing.Color.Green;
                        Label2.Text = " Word File Uploaded Successfully";
                    }
                    else
                    {
                        Label2.ForeColor = System.Drawing.Color.Red;
                        Label2.Text = "Select Only word Files  ";                          // if file is other than speified extension
                    }
                }
                catch (Exception ex)
                {
                    Label2.Text = "Error: " + ex.Message.ToString();
                }
            }
    }

STEP-4:- Now double click on the “View Files” button and write the following code

protected void Button2_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection("server=AJIT;database=Demo;uid=sa;pwd=123");
        SqlDataAdapter da = new SqlDataAdapter("Select *from WordFiles", cn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        cn.Close();

    }

STEP-5:- Now write the following code in GridView  selected index changed event of the gridview

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection("server=AJIT;database=Demo;uid=sa;pwd=123");
        cn.Open();
        SqlCommand com = new SqlCommand("select Name,type,data from  WordFiles where id=@id", cn);
        com.Parameters.AddWithValue("id", GridView1.SelectedRow.Cells[1].Text);
        SqlDataReader dr = com.ExecuteReader();
        if (dr.Read())
        {
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = dr["type"].ToString();
     Response.AddHeader("content-disposition", "attachment;filename=" +   dr["Name"].ToString());     // to open file prompt Box open or Save file        
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.BinaryWrite((byte[])dr["data"]);
            Response.End();
        }
    }

After write all the code now run the page it will look like bellow.