asp.net+jquery.form实现图片异步上传的方法(附jquery.form.js下载)
本文实例讲述了asp.net+jquery.form实现图片异步上传的方法。分享给大家供大家参考,具体如下:
首先我们需要做准备工作:
jquery点击此处本站下载。
jquery.form.js点击此处本站下载。
页面JqueryFormTest.aspx:
<%@PageLanguage="C#"AutoEventWireup="true"CodeFile="JqueryFormTest.aspx.cs"Inherits="JqueryFormTest"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title></title>
<scriptsrc="JS/jquery-1.8.0.js"type="text/javascript"></script>
<scriptsrc="JS/jquery.form.js"type="text/javascript"></script>
<scripttype="text/javascript">
$(function(){
$("#btn").click(function(){
$("#fm1").ajaxSubmit({
url:"img.ashx",
type:"post",
success:function(data){
alert(data);
//IE显示图片会默认加上<PRE></PRE>,着必须要把去除掉才能在低版本ie显示
data=data.replace("<PRE>","").replace("</PRE>","");
$("#divimg").append("<imgsrc='"+data+"'width='200px'height='200px'/>");
//清空file控件里面的值
varfile=$("#btnfile");
file.after(file.clone().val(""));
file.remove();
}
});
});
})
</script>
</head>
<body>
<formid="fm1"method="post">
<!--method="post"不能省略,在ie里面必不可少-->
<inputtype="file"id="btnfile"name="btnfile"value="提交"/>
<br/>
<inputtype="button"id="btn"value="上传"/>
</form>
<divid="divimg">
</div>
</body>
</html>
img.ashx:
<%@WebHandlerLanguage="C#"Class="img"%>
usingSystem;
usingSystem.Web;
publicclassimg:IHttpHandler{
publicvoidProcessRequest(HttpContextcontext){
context.Response.ContentType="text/plain";
//获取上传的文件的对象
HttpPostedFileimg=context.Request.Files["btnfile"];
//获取上传文件的名称
strings=img.FileName;
//截取获得上传文件的名称(ie上传会把绝对路径也连带上,这里只得到文件的名称)
stringstr=s.Substring(s.LastIndexOf("\\")+1);
stringpath="~/upload/"+str;
//保存文件
img.SaveAs(context.Server.MapPath(path));
//HttpRuntime.AppDomainAppVirtualPath主要是获取应用程序虚拟路径名称,因为响应给页面时不会自动添加而导致无法显示图片
context.Response.Write(HttpRuntime.AppDomainAppVirtualPath+path.Substring(1));//path.Substring(1)用来去除第一个~字符
}
publicboolIsReusable{
get{
returnfalse;
}
}
}
更多关于jQuery相关内容感兴趣的读者可查看本站专题:《jQuery切换特效与技巧总结》、《jQuery拖拽特效与技巧总结》、《jQuery扩展技巧总结》、《jQuery常见经典特效汇总》、《jQuery动画与特效用法总结》、《jquery选择器用法总结》及《jQuery常用插件及用法总结》
希望本文所述对大家jQuery程序设计有所帮助。