
正文
使用jQuery.form插件,实现完美的表单异步提交
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="Scripts/jquery-1.10.2.js"></script>
<script src="Scripts/jquery.form.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
$("#fm1").ajaxSubmit({
url: "UpLoadImageHandler.ashx",
type: "post",
success: function (data) {
alert(data);
//IE显示图片会默认加上<PRE></PRE>,着必须要把去除掉才能在低版本ie显示
data = data.replace("<PRE>", "").replace("</PRE>", "");
$("#divimg").append("<img src='" + data + "' width='200px' height='200px'/>");
//清空file控件里面的值
var file = $("#btnfile");
file.after(file.clone().val(""));
file.remove();
}
});
});
})
</script>
</head>
<body>
<form id="fm1" method="post">
<!--method="post"不能省略,在ie里面必不可少-->
<input type="file" id="btnfile" name="btnfile" value="提交" />
<br />
<input type="button" id="btn" value="上传" />
</form>
<div id="divimg">
</div>
</body>
</html>
<%@ WebHandler Language="C#" Class="UpLoadImageHandler" %>
using System;
using System.Web;
public class UpLoadImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//获取上传的文件的对象
HttpPostedFile img = context.Request.Files["btnfile"];
//获取上传文件的名称
string s = img.FileName;
//截取获得上传文件的名称(ie上传会把绝对路径也连带上,这里只得到文件的名称)
);
string path = "~/upload/" + str;
//保存文件
img.SaveAs(context.Server.MapPath(path));
//HttpRuntime.AppDomainAppVirtualPath主要是获取应用程序虚拟路径名称,因为响应给页面时不会自动添加而导致无法显示图片
context.Response.Write(HttpRuntime.AppDomainAppVirtualPath + path.Substring());//path.Substring(1)用来去除第一个~字符
}
public bool IsReusable
{
get
{
return false;
}
}
}







