Consistent UI Across Browsers For File Upload Control

As you all know, the File Upload control in ASP.Net is used to upload your favorite files to a server. One of the biggest challenges when using this control is UI issues. That is, this control is rendered differently in each of the browsers. Please see the following figures, each of them render the File Upload control in a different way in the various browsers. That is, the UI varies across the browsers.
Internet Explorer:


So in this article, I'm showing how to avoid this problem and provide a consistent look and feel across all browsers. Just create an aspx file with the following code:
  1. <!DOCTYPE html>  
  2. <html xmlns="">  
  3. <head runat="server">  
  4.     <title>Uploader Demo</title>  
  5.     <script src="Scripts/jquery-1.8.2.js"></script>  
  6.     <script language="javascript" type="text/javascript">  
  7.         function hookFileClick() {  
  8.             // Initiate the File Upload Click Event  
  9.             document.getElementById('fileUploader').click();  
  10.         }  
  12.         function fnOnChange(obj)  
  13.         {  
  14.             document.getElementById("txtUploadFile").value = obj.value;  
  15.         }  
  16.     </script>  
  17. </head>  
  18. <body>  
  19.     <form id="form1" runat="server">  
  20.         <div>  
  21.             <input type="text" runat="server"   
  22.             id="txtUploadFile" disabled="disabled" />  
  23.             <input type="button" runat="server"   
  24.             id="btnUpload" value="Browse"   
  25.             onclick="hookFileClick()"  />  
  26.             <asp:Button runat="server"   
  27.             ID="btnUploadFileToServer"   
  28.             Text="Upload File To Server"   
  29.             OnClick="btnUploadFileToServer_Click" />  
  30.             <asp:FileUpload runat="server"   
  31.             ID="fileUploader" Style="visibility: hidden;"   
  32.             onchange="fnOnChange(this);" />  
  33.         </div>  
  34.     </form>  
  35. </body>  
  36. </html>  
The following codebehind code is used to save the file into the server:
  1. protected void btnUploadFileToServer_Click(object sender, EventArgs e)  
  2.  {   
  3.       string strFileName = fileUploader.FileName;   
  4.       fileUploader.SaveAs("d:\\Somepath\\ " + strFileName);   
  5.  } 
Code Explanation

I just have one text box (txtUploadFile) and a button (btnUpload) that simulates a File Upload control. Also I have here a File Upload Server Control (fileUploader) whose visibility is set to false. I just hook up the File Upload Server Control click event in the first button's click event. So when you click the first button it will open the file open dialog. These are all done using JavaScript. As a result you get a consistent UI for this control across all browsers.

Internet Explorer



If you have any suggestions, shoot me your thoughts as comments! Happy coding!

Similar Articles