Asp.net file upload validation using javascript and C#

Hi experts,

I have an asp.net webform on which i have various controls like text boxes and a file upload control with browse textbox , button and an upload button.I have a validation check in place for gif image uploads only.When i upload an image, the image gets displayed in an image control.Now, as a negetive testcase, when i manually enter a something in the browse textbox like abc.gif, the extension check gets by passed in javascript.And control doesnot pass on to the c# upload click event.Can you provide some logic for complete validation client and server side?I need to do this using javacsript and c# only.
DevildibAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

jorge_torizResearch & Development ManagerCommented:
With this you would validate that only png files are being uploaded.
<script src="../js/jquery-2.2.0.min.js"></script>
<script>
    var Upload = {};
    Upload.validateExtension = function (o, e) {
        if ($('#fuFile')[0].files.length > 0)
            e.IsValid = $('#fuFile')[0].files[0].type === 'image/png';
        else
            e.IsValid = true;
    }
    Upload.validateSize = function (o, e) {
        if ($('#fuFile')[0].files.length > 0)
            e.IsValid = $('#fuFile')[0].files[0].size > 0;
        else
            e.IsValid = true;
    }
</script>

Open in new window

<asp:FileUpload ID="fuFile" runat="server" />
<asp:RequiredFieldValidator ID="rfvFile" runat="server" ControlToValidate="fuFile" ValidationGroup="Upload" Display="Dynamic"
    ErrorMessage="The file is required">*</asp:RequiredFieldValidator>
<asp:CustomValidator ID="cvFileExtension" runat="server" ControlToValidate="fuFile" ValidationGroup="Upload" Display="Dynamic"
    ErrorMessage="The extension is not valid" ClientValidationFunction="Upload.validateExtension" OnServerValidate="cvFileExtension_ServerValidate">*</asp:CustomValidator>
<asp:CustomValidator ID="cvFileSize" runat="server" ControlToValidate="fuFile" ValidationGroup="Upload" Display="Dynamic"
    ErrorMessage="The file must have at least one byte long" ClientValidationFunction="Upload.validateSize" OnServerValidate="cvFileSize_ServerValidate">*</asp:CustomValidator>
<asp:Button ID="cmdUpload" runat="server" Text="Upload" ValidationGroup="Upload" OnClick="cmdUpload_Click" />
<asp:ValidationSummary ID="vsUpload" runat="server" ValidationGroup="Upload" />

Open in new window

protected void cvFileExtension_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = System.IO.Path.GetExtension(fuFile.FileName) == ".png";
}
protected void cvFileSize_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = fuFile.PostedFile.ContentLength > 0;
}
protected void cmdUpload_Click(object sender, EventArgs e)
{
    Validate("Upload");
    if (IsValid)
    {
        Response.Write("Let's continue with the job");
    }
}

Open in new window

DevildibAuthor Commented:
CAn you provide the javascript function instead of jquery please?
leakim971PluritechnicianCommented:
replace $('#fuFile')[0]
by
document.getElementById("fuFile")
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

DevildibAuthor Commented:
getting files.length is null or not an object.
changed function:

var Upload = {};
Upload.validateExtension = function(o, e) {
    if (getel("fuFile").files.length > 0)
        e.IsValid = getel("fuFile").files[0].type === 'gif';
    else
        e.IsValid = true;
}
Upload.validateSize = function(o, e) {
    if (getel("fuFile").files.length > 0)
        e.IsValid = getel("fuFile").files[0].size > 0;
    else
        e.IsValid = true;
}

Open in new window

leakim971PluritechnicianCommented:
so ?
DevildibAuthor Commented:
Above code is giving errors as mentioned above
leakim971PluritechnicianCommented:
the error is the code don't find the element in the page so we get null and we try to get length of this "null"...

    if (getel("fuFile") && getel("fuFile").files.length > 0)

Open in new window


or better, use  : getel("<%= fuFile.ClientID %>")
    var fuFile = getel("<%= fuFile.ClientID %>");
    if (fuFile && fuFile.length)

Open in new window

jorge_torizResearch & Development ManagerCommented:
Yep, with the ClientID you'll find the control without jquery... can't you find your control yet?

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
DevildibAuthor Commented:
I am sorry, forgot to mention that the getel function i was using is doing nothing but appending the master control text and ultimately making up client id's.The problem is different.On upload button click,i do the validation and the valid gif is displayed nice and fine in the image server control for preview.The file path gets wiped out since its a postback.Now on final submit button of the form, how do i make sure on client side if the image control holds anything?I cannot check the file upload control since upload has already been clicked and file is getting displayed in the image control.
DevildibAuthor Commented:
The fufile.length thing yiu mentioned worked.Just that the final submit button should be vakidating the preview image existance in the inage control.one more thing, when i manually enter an arbitary file name with gif extension, client side validation doesnot validate this.And button click event does'nt fire whether its upload button or final submit button.Why dies this happen?
jorge_torizResearch & Development ManagerCommented:
Well, as far as I know you can't validate the content of a file directly from the client side, I mean that the extension is the only thing you could validate, so if you put a file with that extension, the client side will say "it's fine for me"
DevildibAuthor Commented:
Ok
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.