As I have mentioned earlier, we need two ASPX pages to
implement this technique. The main ASPX page will have the following:
1) A Hyperlink
2) <IFRAME> HTML tag- Source for this IFRAME will be
Upload.aspx
And in the Upload.aspx page, we need to have the following:
1) Input type=file HTML control (Visibility should be
hidden)
2) Submit button (Again, Visibility should be hidden)
When the user clicks on the hyperlink from the main.aspx, we
have to show the File Choose dialog box. This can be done by invoking the
onclick event for the <input type=file> control which resides in the
Upload.aspx. In order to submit the form, we have to fire up the onclick event
for the Submit button which is located in the Upload.aspx. This time we will
not get any client side JavaScript error. Strange you might think; the same
code fails when there is no <IFRAME> involved and the same code works when
an <IFRAME> is involved. Confusing …. but it works like a charm!
Here is the complete code for Main.aspx.
Listing 2
<html>
<head>
<script type="text/javascript" language="javascript">
function Browse()
{
var ifUpload;
var confirmUpload;
ifUpload = frUpload.document.form1;
ifUpload.myFile.click();
ifUpload.btnSubmit.click();
}
</script>
<title>File Upload</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="#" OnClick="javascript:Browse();">Attach Files</a>
<iframe src="Upload.aspx" frameborder="0" id="ifu" name="ifu"></iframe> </div>
</form>
</body>
</html>
Complete code for Upload.aspx is below.
Listing 3
<%@ Page Language="C#"%>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Files.Count == 1)
{
myFile.PostedFile.SaveAs(Server.MapPath(".") +
"\\upload\\myUploadFile.txt");
}
}
</script>
<html>
<head runat="server">
<script type="text/javascript">
function SubmitForm()
{
// Simply, submit the form
document.form1.submit ();
}
</script>
<title>Upload</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="file" runat="server" id="myFile" name="myFile"
style="visibility:hidden;" />
<input type="button" runat="server" id="btnSubmit" name="btnSubmit"
onclick="javascript:SubmitForm();" style="visibility:hidden;" />
<br /><asp:Label ID="lblMsg" runat="server" ForeColor="red"
Font-Size="Medium" Font-Bold="true"></asp:Label>
</div>
</form>
</body>
</html>
If you carefully go through the code listing for
Upload.aspx, you will find that the visibility property of Input type=file control
and the submit button control is set to “Hidden.” If we set the visibility of
these control to visible, then we will see the browse button and the submit
button in the Internet Explorer (Browser). We really need these two controls to
upload any file to a Server from a Client PC.