asp.net使用jquery.form實現圖片異步上傳


首先我們需要做准備工作:

jquery下載:http://files.cnblogs.com/tianguook/jquery1.8.rar

jquery.form.js下載:http://files.cnblogs.com/tianguook/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;
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM