本文實例講述了asp.net+jquery.form實現圖片異步上傳的方法。分享給大家供大家參考,具體如下:
首先我們需要做準備工作:
jquery 點擊此處本站下載。
jquery.form.js 點擊此處本站下載。
頁面JqueryFormTest.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JqueryFormTest.aspx.cs" Inherits="JqueryFormTest" %><!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 src="JS/jquery-1.8.0.js" type="text/javascript"></script> <script src="JS/jquery.form.js" type="text/javascript"></script> <script type="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("<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>
img.ashx:
<%@ WebHandler Language="C#" Class="img" %>using System;using System.Web;public class img : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; //獲取上傳的文件的對象 HttpPostedFile img = context.Request.Files["btnfile"]; //獲取上傳文件的名稱 string s = img.FileName; //截取獲得上傳文件的名稱(ie上傳會把絕對路徑也連帶上,這里只得到文件的名稱) string str = s.Substring(s.LastIndexOf("http://") + 1); string path = "~/upload/"+ str; //保存文件 img.SaveAs(context.Server.MapPath(path)); //HttpRuntime.AppDomainAppVirtualPath主要是獲取應用程序虛擬路徑名稱,因為響應給頁面時不會自動添加而導致無法顯示圖片 context.Response.Write(HttpRuntime.AppDomainAppVirtualPath + path.Substring(1));//path.Substring(1)用來去除第一個~字符 } public bool IsReusable { get { return false; } }}
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery切換特效與技巧總結》、《jQuery拖拽特效與技巧總結》、《jQuery擴展技巧總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》、《jquery選擇器用法總結》及《jQuery常用插件及用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答