mskitten

又惘又怠

页首Html代码

(iframe实现)无刷新上传图片

Index.aspx 页面

   <html>

       <head>

          <title>iframe实现无刷新上传图片</title>

        </head>

  <body>

<input id="photo" name="photo" type="text" style="display: none" />

<iframe id="upfile1" src="addimage/Addimg2.aspx?name=photo" scrolling="no" frameborder="0" width="150px" height="150px"></iframe>

 </body>

 </html>

 

Addimg2.aspx页面

<html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
  <title></title>
<style type="text/css">
 .hidden
 {
      display: none;
  }
</style>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function show() {
document.getElementById('Button1').click();
}
</script>

   <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="上传" CssClass="hidden" />
<div>
   <asp:Image ID="img1" runat="server" CssClass="notShow" Height="80" ImageUrl="~/images/nopic.gif" />
</div>

<div>
   <asp:FileUpload ID="FileUpload1" onchange="show();" runat="server" Width="70" />
</div>
</form>
</body>
</html>

 

Addimg2.aspx.cs 页面

 

protected void Button1_Click(object sender, EventArgs e)
{
String savePath = @"~\Upload\image\";
savePath = Server.MapPath(savePath);
if (!Directory.Exists(savePath))
{
     Directory.CreateDirectory(savePath);
}
if (FileUpload1.HasFile)
{
    String filename;
    filename = FileUpload1.FileName;
    savePath += filename;

    FileUpload1.SaveAs(savePath);
    //相对路径
     string strUrl = UrlConvertor(savePath);
     img1.ImageUrl = "~\\" + strUrl;
     //获取文件后缀名
    //string fileException = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();//获取后缀名

   // 将相对路径返回给父页面
  //Response.Write(string.Format("<script>window.parent.form1.photo.value='{0}';</script>", strUrl));
}
}

/// <summary>
/// 本地路径转换成URL相对路径
/// </summary>
/// <param name="strImagesUrl"></param>
/// <returns></returns>
private string UrlConvertor(string strImagesUrl)
{
    string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//获取程序根目录
    string imagesurl2 = strImagesUrl.Replace(tmpRootDir, ""); //转换成相对路径
    imagesurl2 = imagesurl2.Replace(@"\", @"/");
    imagesurl2 = string.Format("/{0}", imagesurl2);
    return imagesurl2;
}

 

使用服务器控件FileUpload 会导致页面回发,刷新页面。一是用户体验不好,而是当页面存在不是服务器控件的时候,无法保持状态。所以使用iframe链接到另外一个页面来做上传处理,这样就可以避免父页面刷新带来的问题。

posted @ 2014-05-13 18:04  是天  阅读(282)  评论(0)    收藏  举报