asp.net+jquery.form實現圖片非同步上傳的方法(附jquery.form.js下載),

來源:互聯網
上載者:User

asp.net+jquery.form實現圖片非同步上傳的方法(附jquery.form.js下載),

本文執行個體講述了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("\\") + 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;  } }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.