Thursday, June 3, 2010

Upload file to server from webpage using C# asp.net 3.5

Upload file to server from webpage using C# asp.net 3.5

The folder you want to upload you have to have permmission to read/write


using System;
using System.Data;
using System.Configuration;
using System.Collections;
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="uploadfile.aspx.cs" Inherits="uploadfile" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <table style="width:50%;"  align="center">
            <tr>
                <td>
                </td>
                <td align="center">
                    <br />
                    <br />
                    <asp:Label ID="Label2" runat="server"></asp:Label></td>
            </tr>
            <tr>
                <td align="right" valign="top">  
                    <asp:Label ID="Label3" runat="server" Text="Select a File to Upload:"></asp:Label>
                    &nbsp;
                    </td>
                <td align="left" >
                    <asp:FileUpLoad id="FileUpLoad1" runat="server" Height="24px" Width="209px" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <br />
                        </td>
            </tr>
            <tr>
                <td align="right" valign="top">  
                    <asp:Label ID="Label4" runat="server" Text="File Description:"></asp:Label>
                    </td>
                <td align="left" >
                    <asp:TextBox ID="TextBox1" runat="server" Width="120px"></asp:TextBox>
                    <asp:Button id="UploadBtn" Text="Upload File" OnClick="UploadBtn_Click"
                        runat="server" Width="78px" />

                </td>
            </tr>
            <tr>
                <td align="right" valign="top">   &nbsp;</td>
                <td align="center" >
                        <asp:Label ID="Label1" runat="server" Width="416px"></asp:Label></td>
            </tr>
            </table>
             <table style="width: 81%; " align="center">
            <tr>
                <td>
                </td>
                <td align="center" >
                        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                            CellPadding="4" DataSourceID="SqlDataSource1"   DataKeyNames="FLID"
                            ForeColor="#333333" GridLines="None" AutoGenerateDeleteButton="true">
                            <RowStyle BackColor="#EFF3FB" />
                            <Columns>
                            <asp:BoundField DataField="FLID" HeaderText="Id"
                                    SortExpression="FLID" />
                            <asp:BoundField DataField="FLDESC" HeaderText="Description"
                                    SortExpression="FLDESC" />
                                <asp:BoundField DataField="FLFOLDER" HeaderText="Folder"
                                    SortExpression="FLFOLDER"  Visible="false"/>
                                <asp:BoundField DataField="FLNAME" HeaderText="Name"
                                    SortExpression="FLNAME" />
                                <asp:BoundField DataField="FLTYPE" HeaderText="Type"
                                    SortExpression="FLTYPE" />
                                <asp:BoundField DataField="FLDATCR" HeaderText="Date"
                                    SortExpression="FLDATCR" />
                                    <asp:BoundField DataField="FLCO" HeaderText="CO"
                                    SortExpression="FLCO" />
                                     <asp:HyperLinkField  DataNavigateUrlFields="FLNAME"  DataNavigateUrlFormatString="files/{0}"  DataTextField="FLNAME"  HeaderText="Download&nbsp;&nbsp;" />
                            </Columns>
                            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <EditRowStyle BackColor="#2461BF" />
                            <AlternatingRowStyle BackColor="White" />
                        </asp:GridView>
                        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
                            ConnectionString="<%$ ConnectionStrings:JDE_RKConnectionString3 %>"
                           
                             DeleteCommand="delete FROM [BOFLUPD] where FLID=@FLID" >
                             <SelectParameters>
                                <asp:SessionParameter Name="FLCO" SessionField="Usrcop" Type="String" />
                            </SelectParameters>
                        </asp:SqlDataSource>
                        <br />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    &nbsp; &nbsp; &nbsp;
                </td>
            </tr>
        </table>
</asp:Content>

 


using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Data.Common;


public partial class uploadfile : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Usrcop"].ToString() == "ALL")
        {
              SqlDataSource1.SelectCommand = "SELECT  * FROM BOFLUPD";
        }
        else
        {
            SqlDataSource1.SelectCommand = "SELECT  * FROM BOFLUPD WHERE  FLCO='" + Session["Usrcop"].ToString() + "'";
        }
    }

    protected void UploadBtn_Click(object sender, EventArgs e)
    {
        if (FileUpLoad1.HasFile)
        {
            string filePath = FileUpLoad1.PostedFile.FileName;
            string FileType = FileUpLoad1.PostedFile.ContentType;
            //FileUpLoad1.SaveAs(@"C:\\sites\\Single15\\visli\\database\\files\\" + FileUpLoad1.FileName);
            string fn = System.IO.Path.GetFileName(FileUpLoad1.PostedFile.FileName);
            string SaveLocation = Server.MapPath("files") + "\\" + fn;
            try
            {
                FileUpLoad1.PostedFile.SaveAs(SaveLocation);
                // "F"+"-"+DateTime.Now.ToShortTimeString()+"-"+
                Label1.Text = "The file has been uploaded.";
                insFileName(FileUpLoad1.FileName, FileType);
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.Message);
                //Note: Exception.Message returns a detailed message that describes the current exception.
                //For security reasons, we do not recommend that you return Exception.Message to end users in
                //production environments. It would be better to put a generic error message.
            }

        }
    }

    void insFileName(string FileName, string FileType)
    {

        SqlConnection myConnection = new SqlConnection(ConnectionString);
        string strSQL;
        string FileFolder = "http://localhost/bioprj/files/" + FileName;
        strSQL = "insert into BOFLUPD(FLFOLDER,FLNAME,FLTYPE,FLDATCR,FLDESC,FLCO)values(@FLFOLDER,@FLNAME,@FLTYPE,@FLDATCR,@FLDESC,@FLCO)";
        SqlCommand cmd = new SqlCommand(strSQL, myConnection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@FLFOLDER", FileFolder);
        cmd.Parameters.AddWithValue("@FLNAME", FileName);
        cmd.Parameters.AddWithValue("@FLTYPE", FileType);
        cmd.Parameters.AddWithValue("@FLDATCR", DateTime.Now.ToShortDateString());
        cmd.Parameters.AddWithValue("@FLDESC", TextBox1.Text);
        cmd.Parameters.AddWithValue("@FLCO", Session["Usrcop"].ToString());
      

        myConnection.Open();
        cmd.ExecuteNonQuery();
        myConnection.Close();
        Label1.Text = "Added..";
        Response.Redirect("uploadfile.aspx");
    }

 

    private string ConnectionString
    {
        get
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
            return connectionString;
        }
    }
}

 

 

No comments: