Validate whether File is selected in FileUpload on Server Side (Code Behind) in ASP.Net

Last Reply 9 days ago By pandeyism

Posted 9 days ago

Hi i have an application that is advertising jobs. i want user to upload their CV. The must do this. I have upload button that takes them to their file explorer. I also have a label showing when the name when they choose a file. I want to validate this to ensure they cannot submit the application until they attach a file

Posted 9 days ago

I am checking it, I will get back to you soon


Posted 9 days ago

Hi Ramo,

Please refer below sample.

HTML

<div>
    <asp:FileUpload ID="fuCV" runat="server" onchange="getFileName(this);" />
    <asp:Button ID="btnSubmit" runat="server" Text="Upload" OnClick="btnSubmit_Click" />
    <br />
    <asp:Label ID="lblMessage" runat="server" />
</div>
<script type="text/javascript">
    function getFileName(ele) {
        document.getElementById('<%=lblMessage.ClientID %>').innerHTML = ele.value.split('\\')[ele.value.split('\\').length - 1];
    }
</script>

Namespaces

C#

using System.IO;

Code

C#

protected void btnSubmit_Click(object sender, EventArgs e)
{
    if (fuCV.HasFile)
    {
        string filename = fuCV.PostedFile.FileName;
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('File uploaded successfully.')", true);
    }
    else
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Please select file.')", true);
    }
}

Screenshot