Javascript – Opening asp Fileupload control from javascript

asp.netc#-3.0file uploadjavascript

I have a asp Fileupload control on my aspx page as follows:

I have a asp button. On ClientClick of this button I am opening the fileupload control from javascript as follows:

———javascript ————-

 function OpenFileDialog() {
 var result = document.getElementById(("<%=fu_Import.ClientID %>")).click();            
        return true;
    }

The fielDialog opens properly , but when I select any file and Click on Open button in that FileDailog nothing happens. I mean the Onclick event of that Asp:Button is not called. Also the filename property of fileUpload control is not set.

protected void btnImportIdiomCSV_Click(object sender, EventArgs e)
{
    try
    {                  
        if (fu_Import.PostedFile.FileName == string.Empty)
        {
          // Error meessage
        }
        else
        {
            // Do something
        }

Best Answer

I'm pretty sure you're going to have to add your code to the Page_Load method and check the following:

  1. if you're posting back
  2. if the PostedFile file length is not zero

In your case it's not the click event of the button which is causing the postback, that's why it's not getting called.

Usually folks do upload after the clicking of a save button, or something along those lines.