制作时间 2009/11/3 4:00-7:00 18:00-20:20
快速回顾
1.目标:页面无刷新 上传图片(fileupload+iframe)
2.原理:只刷新iframe内的控件
1.MainPage.aspx有个iframe,它的src是一个页面UpLoadPic.aspx
2.UpLoadPic.aspx里有一个FileUpLoad和"上传"按钮
3.基本实现:
1.新建页面MainPage_Base.aspx,并在根目录新建一个文件夹images
<div>
<iframe id="file" name="file" src="UpLoadPic.aspx"></iframe><br />
</div>
2.新建页面UpLoadPic.aspx
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="上传" OnClick="Button1_Click" />
</div>
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string pic = string.Format("~/images/{0}",FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath(pic));
}
}
3.点"上传"按钮后,"刷新"文件夹images,就可以看到文件了
4.测试:如何知道是局部刷新了呢? (虽然"后退"按钮可以使用,但确实实现了局部刷新)
1.在MainPage.aspx的<iframe...></iframe>后面加上
<input id="abc" type="text" />
<asp:Button ID="Button2" runat="server" Text="Button" />
2.在页面打开后,手动在文本框中输入一些数据("dafa")
然后,分别点Button1 和Button2,会发现点Button1后,文本框数据还存在
而点Button2后,文本框数据消失
说明点Button1只刷新了iframe,而点Button2则刷新了整个页面
5.比较完整的实现
1.得到fileupload上传文件的路径(通过回传 top.callBack('path');)
2.上传图片的时候,有缩略图可以显示
1.新建页面MainPage_Normal.aspx,并在根目录新建一个文件夹images
1.加了隐藏域和回调函数(为了得到文件上传的路径)
<script type="text/javascript">
function callBack(fileName)
{
document.getElementById("<%=HiddenField1.ClientID %>").value=fileName;
}
</script>
<iframe id="file" name="file" src="UpLoadPic.aspx" width="300" height="200" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no" allowtransparency="true"></iframe><br />
<asp:HiddenField ID="HiddenField1" runat="server" />
<input id="abc" type="text" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
protected void Button1_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(GetType(),"11","alert('"+HiddenField1.Value+"')",true);
}
2.新建页面UpLoadPic.aspx
1.加了img显示缩略图
2.在上传按钮事件里,注册了JavaScript回调函数
<script type="text/javascript">
function preview(picpath)
{
document.getElementById("imgshow").src=picpath
}
</script>
<div>
<asp:FileUpload ID="FileUpload1" runat="server" BackColor="White"
onchange="preview(this.value)" />
<asp:Button ID="Button1" runat="server" Text="上传" OnClick="Button1_Click"
Height="22px" BackColor="#FFC0FF" Width="51px" />
<img id="imgshow" src="" alt="" />
</div>
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string pic = string.Format("~/images/{0}",FileUpload1.FileName);
FileUpload1.SaveAs(Server.MapPath(pic));
ClientScript.RegisterStartupScript(GetType(), "callBackFileName",
"top.callBack('"+pic+"')", true);
}
}