Friday, December 3, 2021

How to upload file in asp.net(File upload control) - Custom validator - Server side validation ASP.NET c#

 https://www.c-sharpcorner.com/article/Asp-Net-2-0-fileupload-control/


or advance functioning


HTML code(aspx)


<div id="Div_Invoice_CF" runat="server" visible="false">

                    <asp:FileUpload ID="fld_Invoice_CF" CssClass="form-control" runat="server" />

                    <asp:CustomValidator ID="CustomValidator1" runat="server"  Display="Dynamic" ForeColor="Red"

                            ErrorMessage="" ValidationGroup="a" SetFocusOnError="true" ControlToValidate="fld_Invoice_CF"

                            OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="None"

                                ErrorMessage="Please Upload Invoice Copy" ControlToValidate="fld_Invoice_CF"

                                ValidationGroup="a" CssClass="ValidatorCallout" SetFocusOnError="True"></asp:RequiredFieldValidator>

                            <cc1:ValidatorCalloutExtender ID="ValidatorCalloutExtender1" runat="server" TargetControlID="RequiredFieldValidator24">

                            </cc1:ValidatorCalloutExtender>

                    <span style="padding:15px">

                        <asp:HyperLink ID="HL_InvoiceUploaded_CF" runat="server" Text="Invoice Copy" Target="_blank" Visible="false"></asp:HyperLink>

                    </span>

                </div>

<div id="Div_Button" runat="server" visible="false" class="col-md-12" style="margin:0 auto; text-align:center">

                <asp:Button ID="btn_Upload" CssClass="btn btn-success" OnClientClick="return confirm('Are you sure to Upload Invoice ?');" runat="server" ValidationGroup="a"

                    Text="Upload" onclick="btn_Upload_Click" /> &nbsp;

                <asp:Button ID="btn_Cancel" CssClass="btn btn-danger" runat="server" Text="Cancel" onclick="btn_Cancel_Click" />

            </div>

cs file code


protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)

    {

        args.IsValid = true;

        string fileextension = Path.GetExtension(args.Value);

        string[] extension = { ".pdf", ".PDF" };

        if (extension.Contains(fileextension))

        {

            if (fld_Invoice.FileBytes.Length > 1024000)

            {

                args.IsValid = false;

                ((CustomValidator)source).IsValid = false;

                CustomValidator2.ErrorMessage = "File Size Cannot Exceed More Than 1 MB";

                return;


            }

            else

            {

                args.IsValid = true;

            }

        }

        else

        {

            args.IsValid = false;

            ((CustomValidator)source).IsValid = false;

            CustomValidator2.ErrorMessage = "Invalid File Type";

            return;

        }

    }

protected void btn_Upload_Click(object sender, EventArgs e)

    {

 if (CustomValidator1.IsValid == true)

            {

        if (Session["trainingpartnercode"] != null && Session["trainingpartnercode"].ToString().Length > 1)

        {

            if (Lbl_InvoiceID.Text != "" && Lbl_InvoiceBatch.Text != "" && Lbl_InvoiceKIA.Text != "")

            {

                string Upload_Invoice_CF = null;

                string Upload_Invoice = null;


                if (fld_Invoice_CF.HasFile)

                {

                    string filename1 = Path.GetFileNameWithoutExtension(fld_Invoice_CF.FileName);

                    string extension1 = Path.GetExtension(fld_Invoice_CF.FileName);

                    string InvoiceALL1 = filename1 + "_" + new Random().Next(7000).ToString() + extension1;

                    Upload_Invoice_CF = InvoiceALL1;

                }


                if (fld_Invoice.HasFile)

                {

                    string filename = Path.GetFileNameWithoutExtension(fld_Invoice.FileName);

                    string extension = Path.GetExtension(fld_Invoice.FileName);

                    string InvoiceALL = filename + "_" + new Random().Next(7000).ToString() + extension;

                    Upload_Invoice = InvoiceALL;

                }


                String KIA_Name = "";

                if (Lbl_InvoiceKIA.Text == "1")

                {

                    KIA_Name = "KIA-NIELIT";

                }

                else if (Lbl_InvoiceKIA.Text == "2")

                {

                    KIA_Name = "KIA-ESSCI";

                }

                else if (Lbl_InvoiceKIA.Text == "3")

                {

                    KIA_Name = "KIA-TSSC";

                }

                else

                {

                    KIA_Name = "";

                }


                if (ViewState["CSRF"] != null && Convert.ToString(ViewState["CSRF"]) == Session["randomno"].ToString())

                {

                    if (Page.IsValid)

                    {


                        try

                        {

                            string UserQuery = @"Update T005_InvoiceDetails 

                                            set 

                                            I_TP_InvoiceUpload_CF=@I_TP_InvoiceUpload_CF,

                                            I_TP_InvoiceUpload_CF_UpdateBy=@I_TP_InvoiceUpload_UpdateBy,

                                            I_TP_InvoiceUpload_CF_UpdateOn=CURRENT_TIMESTAMP,

                                            I_TP_InvoiceUpload=@I_TP_InvoiceUpload,

                                            I_TP_InvoiceUpload_UpdateBy=@I_TP_InvoiceUpload_UpdateBy,

                                            I_TP_InvoiceUpload_UpdateOn=CURRENT_TIMESTAMP

                                            where I_ID=@I_ID";

                            object ob = null;

                            ob = Luminious.DataAcessLayer.SqlHelper.ExecuteScalar(Luminious.Connection.Configuration.ConnectionString, CommandType.Text,

                               UserQuery,

                               new SqlParameter[] { 

                        new SqlParameter("@I_TP_InvoiceUpload_CF", Upload_Invoice_CF),

                        new SqlParameter("@I_TP_InvoiceUpload", Upload_Invoice),

                        new SqlParameter("@I_TP_InvoiceUpload_UpdateBy", Session["trainingpartnercode"] != null ? Convert.ToString(Session["trainingpartnercode"]) : null),  

                        new SqlParameter("@I_ID", Convert.ToInt64(Lbl_InvoiceID.Text))  

                        });


                            //For update log

                            Update_Invoice_Log(Convert.ToInt64(Lbl_InvoiceID.Text), Convert.ToInt64(Lbl_InvoiceBatch.Text), KIA_Name, "Invoice Uploaded", Convert.ToString(Session["trainingpartnercode"]));


                            try

                            {

                                BLL_LoginAudit objAudit = new BLL_LoginAudit();

                                objAudit.Transction(new BO_LoginAuditMaster

                                {

                                    Login_action = "I",

                                    Login_Action_Type = "Invoice Uploaded/" + Convert.ToString(Lbl_InvoiceID.Text),

                                    Login_Audit_id = 0,

                                    Login_Date_Time = DateTime.Now,

                                    Login_IP_Address = LuminiousUtility.Util.Utility.VisitorIPAddress(),

                                    Login_Module_Name = "Training Partner",

                                    Login_Section_Name = LuminiousUtility.Util.Utility.BrowserDetection(),

                                    Login_Status = "Success",

                                    Login_User_Name = Convert.ToString(Session["trainingpartnercode"]),

                                    Login_User_Type = 5

                                });

                            }

                            catch (Exception ee)

                            {

                                ExceptionHandler.WriteException(ee.Message);

                            }


                            if (fld_Invoice.HasFile)

                            {

                                if (fld_Invoice_CF.HasFile)

                                {

                                    fld_Invoice_CF.SaveAs(MapPath("..\\TPDocument\\Invoice\\" + Upload_Invoice_CF));

                                }


                                fld_Invoice.SaveAs(MapPath("..\\TPDocument\\Invoice\\" + Upload_Invoice));


                                ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "alert('Invoice uploaded Successfully');", true);


                                #region redirectbtmeta

                                HtmlMeta meta = new HtmlMeta();


                                meta.HttpEquiv = "Refresh";


                                meta.Content = "1;url=InvoiceInbox.aspx";


                                this.Page.Controls.Add(meta);

                                #endregion

                            }

                            else

                            {

                                try

                                {

                                    BLL_LoginAudit objAudit = new BLL_LoginAudit();

                                    objAudit.Transction(new BO_LoginAuditMaster

                                    {

                                        Login_action = "I",

                                        Login_Action_Type = "TP Invoice Upload Error",

                                        Login_Audit_id = 0,

                                        Login_Date_Time = DateTime.Now,

                                        Login_IP_Address = LuminiousUtility.Util.Utility.VisitorIPAddress(),

                                        Login_Module_Name = "Training Partner",

                                        Login_Section_Name = LuminiousUtility.Util.Utility.BrowserDetection(),

                                        Login_Status = "Success",

                                        Login_User_Name = Convert.ToString(Session["trainingpartnercode"]),

                                        Login_User_Type = 5

                                    });

                                }

                                catch (Exception ee)

                                {

                                    ExceptionHandler.WriteException(ee.Message);

                                }


                                ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "alert('Error Occured');", true);

                            }


                        }

                        catch (Exception ee)

                        {

                            ExceptionHandler.WriteException(ee.Message);

                        }

                        finally

                        {

                            GC.SuppressFinalize(this);

                            CrossSiteRequestForgery();

                            CreateRandomHashing();

                        }

                    }

                    else

                    {

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "alert('Error Occured');", true);

                    }

                }

                else

                {

                    CrossSiteRequestForgery();

                }

            }

            else

            {

                ScriptManager.RegisterStartupScript(this, this.GetType(), "message", "alert('Insufficient Information');", true);

            }

        }

        else

        {

            Response.Redirect("~/Login.aspx?errormessage=No valid session found", false);

        }

}

    }


protected void btn_Cancel_Click(object sender, EventArgs e)

    {       

        Response.Redirect("InvoiceUpload.aspx");


    }



------------------------------

or


if (fld_NPRCard.HasFile)

            {

                string filename9 = Path.GetFileNameWithoutExtension(fld_NPRCard.FileName);

                string extension9 = Path.GetExtension(fld_NPRCard.FileName);

                Upload_Identity_Proof_Document_NPR = filename9 + "_" + ustring + extension9;

                fld_NPRCard.SaveAs(Server.MapPath("..\\StudentData\\Certificate\\" + Upload_Identity_Proof_Document_NPR));

            }

No comments:

Post a Comment