C#中使用iframe结合js实现图片异步上传

来源:互联网 发布:俄罗斯酗酒知乎 编辑:程序博客网 时间:2024/06/05 21:50

将图片上传的页面放在iframe中,通过iframe跳转到另一个页面,在该页中将图片提交到服务器,而不需要对主页进行刷新,提交成功后用脚本(回调函数)实现上传的图片在主页面的显示。

图片选择页面 Add.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Add.aspx.cs" Inherits="_Add" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server">    <title></title>    <script type="text/javascript">//图片异步上传function doUpload() {var theFrame = document.getElementById("uploadframe");if (theFrame) {theFrame = theFrame.contentWindow;theFrame.selectAndUpload();}}function callback(str) {var theImg = document.getElementById("imgResult");document.getElementById("picUrl").value = str;str = "../images/" + str;theImg.setAttribute("src", str);}    </script></head><body>    <form id="form1" runat="server">    <div>        <iframe src="Print/PicUpload.aspx" id="uploadframe" style="display: none;"></iframe>        <p>            <asp:Image ID="imgResult" runat="server" Width="80" Height="112" />        </p>        <p>            <input type="button" id="btnBrowser" value="选择文件" onclick="doUpload()" />        </p>        <h5>            上传图片格式为.jpg, .gif, .bmp,.png,图片大小不得超过8M</h5>    </div>    <input id="picUrl" type="hidden" runat="server" value="" />    </form></body></html>

图片上传处理页面

前台 PicUpload.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PicUpload.aspx.cs" Inherits="Web.Print.PicUpload" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>无标题页</title>         <script type="text/javascript">        function selectAndUpload() {            var theFileUpload = document.getElementById("<%=pic_upload.ClientID%>");            theFileUpload.onchange = function () {                var fileExt = theFileUpload.value.substr(theFileUpload.value.lastIndexOf("."));                                //判断文件打大小                if(theFileUpload.files[0].size>8192000)                {                     top.alert("文件大小超出8M!请重新选择!");                }                else                {        //验证是不是图片                                 if (!fileExt.match(/\.jpg|\.png|\.bmp|\.gif/i))                         {                            top.alert("只能上传jpg,gif,bmp,png图片!");                        }                        else {                            var myForm = document.getElementById("<%=form1.ClientID%>");                            myForm.submit();                        }                  }            }            theFileUpload.click();        }        //回调函数        function callback(filePath)         {             parent.callback(filePath);             //也可用top.callback,But,若Add.aspx是其他页面通过iframe 跳转到的(如在index.aspx 通过<iframe src="Add.aspx"></iframe> 跳转到Add.aspx),             //则top.callback无法回调到Add.aspx,而parent.callback可以回调到Add.aspx        }  </script> </head><body>    <form id="form1" runat="server">    <asp:ScriptManager ID="ScriptManager1" runat="server" >    </asp:ScriptManager>    <div>      <asp:FileUpload runat="server" ID="pic_upload"></asp:FileUpload>      </div>    </form></body></html>
后台图片上传事件及促发回调函数处理

PicUpload.aspx.cs:

using System;using System.Collections;using System.Configuration;using System.Data;using System.Linq;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Xml.Linq;using System.IO;using System.Security.Cryptography;namespace Web.Print{    public partial class PicUpload : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            if (IsPostBack && pic_upload.HasFile)            {                               //取得文件的扩展名,并转换成小写                string fileExtension = Path.GetExtension(pic_upload.FileName).ToLower();                string filepath = "/images/";                if (Directory.Exists(Server.MapPath(filepath)) == false)//如果不存在就创建file文件夹                {                    Directory.CreateDirectory(Server.MapPath(filepath));                }                string hash = CreatePasswordHash(pic_upload.FileName, 4);                string virpath = filepath + hash + fileExtension;//这是存到服务器上的虚拟路径                string mappath = Server.MapPath(virpath);//转换成服务器上的物理路径                pic_upload.SaveAs(mappath);                                                                            ScriptManager.RegisterStartupScript(this, this.GetType(), "callback", "callback('" + hash + fileExtension + "');", true);            }        }                      /// <summary>        /// 创建一个指定长度的随机salt值        /// </summary>        public string CreateSalt(int saltLenght)        {            //生成一个加密的随机数            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();            byte[] buff = new byte[saltLenght];            rng.GetBytes(buff);            //返回一个Base64随机数的字符串            return Convert.ToBase64String(buff);        }        /// <summary>        /// 返回加密后的字符串        /// </summary>        public string CreatePasswordHash(string pwd, int saltLenght)        {            string strSalt = CreateSalt(saltLenght);            //把密码和Salt连起来            string saltAndPwd = String.Concat(pwd, strSalt);            //对密码进行哈希            string hashenPwd = FormsAuthentication.HashPasswordForStoringInConfigFile(saltAndPwd, "sha1");            //转为小写字符并截取前16个字符串            hashenPwd = hashenPwd.ToLower().Substring(0, 16);            //返回哈希后的值            return hashenPwd;        }    }}






0 0
原创粉丝点击