Asp.net file upload validation using javascript and C#

Devildib
Devildib used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
jorge_torizResearch & Development Manager
Commented:
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

Author

Commented:
CAn you provide the javascript function instead of jquery please?
leakim971Multitechnician
Top Expert 2014
Commented:
replace $('#fuFile')[0]
by
document.getElementById("fuFile")
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Author

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

leakim971Multitechnician
Top Expert 2014

Commented:
so ?

Author

Commented:
Above code is giving errors as mentioned above
leakim971Multitechnician
Top Expert 2014

Commented:
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

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

Author

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.

Author

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 Manager

Commented:
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"

Author

Commented:
Ok

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial