Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Is there any way to call a function directly after selecting a file in the FileUpload control? Can we do it without having to click a button?

The function I want to call immediately after selecting the file is FileSelected(). After that the function FileSelected() calls another function called CheckFileType().

I do want to use a button afterwards to save the file, but not for calling the function.

What I have tried:

private void FileSelected()
{
    if (FileUpload1.HasFile)
    {
        if (CheckFileType(FileUpload1.FileName))
        {
            String filePath = "Cert/" + FileUpload1.FileName;
            txtpath1.Text = filePath;
        }
        else
        {
            Label1.Visible = true;
            Label1.Text = "You can upload ony images or PDF files.";
        }
    }
}

private bool CheckFileType(string fileName)
{
    string ext = Path.GetExtension(fileName);
    switch (ext.ToLower())
    {
        case ".gif":
        case ".png":
        case ".jpg":
        case ".jpeg":
        case ".pdf":
            return true;
        default:
            return false;
    }

}
Posted
Updated 19-Feb-18 8:39am
v2
Comments
j snooze 19-Feb-18 17:08pm    
This might be more helpful.
https://www.w3schools.com/tags/att_input_accept.asp
Laxmidhar tatwa technologies 19-Feb-18 23:28pm    
switch (ext.ToLower())
{
case ".gif":
case ".png":
case ".jpg":
case ".jpeg":
case ".pdf":
return true;
break;
default:
return false;
}
Laxmidhar tatwa technologies 19-Feb-18 23:28pm    
after return true breake; should be there

1 solution

You can use the onchange event of the fileupload control

JavaScript Fileupload Object : onchange Event handlers - w3resource[^]

It's not going to work for what you want to do though. The file you have selected can't be "remembered" between postbacks so if you click a button programatically, or do anything else to send the file to the server like submit the form, then your code will check the file extension but when the page returns the file control will be empty again and there is nothing you can do about that.

So if you want to check the file's extension before you upload you need to do it via javascript. You still need your server-code as well though as malicious people can bypass your javascript.

There are various of doing that if you google but here are some

Validate file upload with html5 file api – BinaryTides[^]

Check File Size & Extension Before Uploading Using jQuery | All PHP Tricks[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900