首先在index.aspx中这样写
<script type="text/javascript" language="javascript">
function Browse()
{
var ifUpload;
var confirmUpload;
ifUpload = ifu.document.form1;
ifUpload.myFile.click();
}
</script>
<title>File Upload</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblStart" runat="server"></asp:Label>
<a href="#" OnClick="javascript:Browse();">增加文件</a>
<iframe src="Upload.aspx" frameborder="0" id="ifu" name="ifu"></iframe>
</div>
</form>
这里,有一个iframe,指向upload.aspx,当用户点“增加文件”时,首先是调用javascript的browse()了。在这里,先看下upload.aspx先
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string strFileName;
string strFileExtension;
int intLastIndex;
if (Request.Files.Count == 1)
{
try
{
strFileName = myFile.PostedFile.FileName;
intLastIndex = strFileName.LastIndexOf("\\");
if (intLastIndex > 0)
{
intLastIndex += 1;
strFileName = strFileName.Substring(intLastIndex, (strFileName.Length - intLastIndex));
strFileExtension = strFileName.Substring(strFileName.Length - 4, 4);
if (strFileExtension == ".txt")
{
myFile.PostedFile.SaveAs(Server.MapPath(".") + "\\" + strFileName);
lblMsg.Text = strFileName + " Uploaded Sucessfully!";
}
else
{
lblMsg.Text = "Only Text File (.txt) can be uploaded.";
}
}
else
{
lblMsg.Text = "Please Select a File!";
}
}
catch (Exception exc)
{
lblMsg.Text = exc.Message;
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript">
function SubmitForm()
{
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>
submitform里,则提交了表单,同时load()里则是实际的上传代码。
同样,在main.aspx中,ifUpload.myFile.click();其实是调用了upload.aspx中的那个上传文件框,首先打开了这个文件框,然后当选定文件后,则通过
ifUpload.btnSubmit.click();实际上调用了那个“上传”的按钮了,从而完成整个过程