Introduction
"I want to use a "file open dialog box" control in my web application.", sounds like a common and most frequently asked question. Even I had the same question and started searching for
a solution, but believe me, it was very hard to get a solution for this and with some help, I came out with a solution and thought I will share it with all my friends out here.
Using the Code
A web application of course wouldn't have any of the standard OS controls. It's a web application, not a fat client application. The only reason to ever present
the user with a "File" dialog box is so they can upload a file. The standard HTML "file input" form element has been around for ages for just
that reason: System.Web.UI.HtmlControls.HtmlInputFile
.
That's the control I'll be using and working around to make things easier and achieve what I want. This is the code snippet which does all the magic:
<script type="text/javascript"language="javascript">
function getFile()
{
document.getElementById("file1").click();
var file = "";
if(document.getElementById("TextBox1").value == "")
file = document.getElementById("file1").value;
else
file = document.getElementById("TextBox1").value +
"\r\n" + document.getElementById("file1").value;
document.getElementById("TextBox1").value = file ;
}
</script>
Include this code in the header of the ASPX of the form.
The three controls which are needed are:
- ASP
Button
control
<asp:ButtonID="Button1" runat="server" OnClick="Button1_Click"
Style="left: 637px; position: absolute; top: 303px"
Text="Button" Width="65px" />
- ASP
TextBox
control
<asp:TextBoxID="TextBox1" runat="server" Height="12px" Width="9px">
</asp:TextBox>
- HTML
FileUpload
control
<inputid="File1" type="file" style=
"width:119px;left:238px;position:absolute;top:41px;visibility:hidden;"
/>
Remember the "Visibility : Hidden
" option in the style
attribute of the HTML FileUpload
control that is required and will do all the trick required
to achieve what is required. It helps you hide the original HTML FileUpload
control and lets all the work be done on button click, and then at the end, you can see the selected
file path in the ASP TextBox
control. You can place it in any of the other controls or use it for further processing.
Points of Interest
I hope this will help many others who are here searching for a solution, but remember, it works in Microsoft's IE only, but there's a solution to make it work
in Firefox Mozilla too.. ha ha.. keep searching for that guys… good luck.