原理:将图片上传的页面放在iframe中,这样就可以在iframe中将图片提交到服务器而不需要页面刷新,提交成功后用脚本实现主页面显示上传的图片。 Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!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 doUpload() {
var theFrame = document.getElementById("uploadframe");
if (theFrame) {
theFrame = theFrame.contentWindow;
theFrame.selectAndUpload();
}
} function callback(str) {
var theImg = document.getElementById("imgResult");
theImg.setAttribute("src", str);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
Asp.net 异步上传示例</h1>
<iframe src="PicUpload.aspx" id="uploadframe" style="display: none;"></iframe>
<p>
<input type="button" id="btnBrowser" value="选择文件" onclick="doUpload()" />
</p>
<h2>
上传结果</h2>
<p>
<img alt="上传后的图片" id="imgResult" style="width: 400px" />
</p>
</div>
</form>
</body>
</html> --------------------------
PicUpload.aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="PicUpload.aspx.cs" Inherits="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("<%=fileUpload1.ClientID%>");
theFileUpload.onchange = function () {
var fileExt = theFileUpload.value.substr(theFileUpload.value.lastIndexOf("."));
if (!fileExt.match(/\.jpg|\.png|\.gif/i))//验证一下是不是图片
{
top.alert("只能上传jpg,png,gif图片。");
}
else {
var myForm = document.getElementById("<%=form1.ClientID%>");
myForm.submit();
}
}
theFileUpload.click();
} function callback(filePath) {
top.callback(filePath);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload runat="server" ID="fileUpload1"></asp:FileUpload>
</div>
</form>
</body>
</html> PicUpload.aspx.cs: using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class PicUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && fileUpload1.HasFile)
{
string path = Server.MapPath("~/upload/" + fileUpload1.FileName);
fileUpload1.SaveAs(path);
ClientScript.RegisterClientScriptBlock(this.GetType(), "callback", "callback('upload/" + fileUpload1.FileName + "')", true);
}
}
}