jQuery外掛程式之ajaxFileUpload

來源:互聯網
上載者:User
ajaxFileUpload.js 很多同名的,因為做出來一個很容易。
我用的是這個:https://github.com/carlcarl/AjaxFileUpload
下載地址在這裡:http://files.cnblogs.com/files/kissdodog/ajaxfileupload_JS_File.rar
AjaxFileUpload.js並不是一個很出名的外掛程式,只是別人寫好的放出來供大家用,原理都是建立隱藏的表單和iframe然後用JS去提交,獲得傳回值。
當初做了個非同步上傳的功能,選擇它因為它的配置方式比較像jQuery的AJAX,我很喜歡。
評論裡面說到的不行。那是因為我們用的不是同一個js。我上github搜AjaxFileUpload出來很多類似js。
ajaxFileUpload是一個非同步上傳檔案的jQuery外掛程式

  傳一個不知道什麼版本的上來,以後不用到處找了。
  文法:$.ajaxFileUpload([options])
  options參數說明:

1、url           上傳處理常式地址。  
2,fileElementId      需要上傳的檔案域的ID,即<input type="file">的ID。
3,secureuri        是否啟用安全提交,預設為false。
4,dataType        伺服器返回的資料類型。可以為xml,script,json,html。如果不填寫,jQuery會自動判斷。
5,success        提交成功後自動執行的處理函數,參數data就是伺服器返回的資料。
6,error          提交失敗自動執行的處理函數。
7,data           自訂參數。這個東西比較有用,當有資料是與上傳的圖片相關的時候,這個東西就要用到了。
8, type           當要提交自訂參數時,這個參數要設定成post

錯誤提示:

1,SyntaxError: missing ; before statement錯誤
  如果出現這個錯誤就需要檢查url路徑是否可以訪問
2,SyntaxError: syntax error錯誤
  如果出現這個錯誤就需要檢查處理提交操作的伺服器幕後處理程式是否存在語法錯誤
3,SyntaxError: invalid property id錯誤
  如果出現這個錯誤就需要檢查文本域屬性ID是否存在
4,SyntaxError: missing } in XML expression錯誤
  如果出現這個錯誤就需要檢查檔案name是否一致或不存在
5,其它自訂錯誤
  大家可使用變數$error直接列印的方法檢查各參數是否正確,比起上面這些無效的錯誤提示還是方便很多。

使用方法:

第一步:先引入jQuery與ajaxFileUpload外掛程式。注意先後順序,這個不用說了,所有的外掛程式都是這樣。

<script src="jquery-1.7.1.js" type="text/javascript"></script><script src="ajaxfileupload.js" type="text/javascript"></script>
第二步:HTML代碼:
<body>    <p><input type="file" id="file1" name="file" /></p>    <input type="button" value="上傳" />    <p><img id="img1" alt="上傳成功啦" src="" /></p></body>
第三步:JS代碼

    <script src="jquery-1.7.1.js" type="text/javascript"></script>    <script src="ajaxfileupload.js" type="text/javascript"></script>    <script type="text/javascript">        $(function () {            $(":button").click(function () {                ajaxFileUpload();            })        })        function ajaxFileUpload() {            $.ajaxFileUpload            (                {                    url: '/upload.aspx', //用於檔案上傳的伺服器端請求地址                    secureuri: false, //是否需要安全性通訊協定,一般設定為false                    fileElementId: 'file1', //檔案上傳域的ID                    dataType: 'json', //傳回值類型 一般設定為json                    success: function (data, status)  //伺服器成功響應處理函數                    {                        $("#img1").attr("src", data.imgurl);                        if (typeof (data.error) != 'undefined') {                            if (data.error != '') {                                alert(data.error);                            } else {                                alert(data.msg);                            }                        }                    },                    error: function (data, status, e)//伺服器響應失敗處理函數                    {                        alert(e);                    }                }            )            return false;        }    </script>
第四步:後台頁面upload.aspx代碼:

protected void Page_Load(object sender, EventArgs e)        {            HttpFileCollection files = Request.Files;            string msg = string.Empty;            string error = string.Empty;            string imgurl;            if (files.Count > 0)            {                files[0].SaveAs(Server.MapPath("/") + System.IO.Path.GetFileName(files[0].FileName));                msg = " 成功! 檔案大小為:" + files[0].ContentLength;                imgurl = "/" + files[0].FileName;                string res = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + imgurl + "'}";                Response.Write(res);                Response.End();            }        }
來一個MVC版本的執行個體:
控制器代碼
public class HomeController : Controller    {        public ActionResult Index()        {            return View();        }        public ActionResult Upload()        {            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;            string imgPath = "";            if (hfc.Count > 0)            {                imgPath = "/testUpload" + hfc[0].FileName;                string PhysicalPath = Server.MapPath(imgPath);                hfc[0].SaveAs(PhysicalPath);            }            return Content(imgPath);        }    }
前端視圖,HTML與JS代碼,成功上傳後,返回圖片真真實位址並綁定到<img>的SRC地址
<html><head>    <script src="/jquery-1.7.1.js" type="text/javascript"></script>    <script src="/ajaxfileupload.js" type="text/javascript"></script>    <script type="text/javascript">        $(function () {            $(":button").click(function () {                if ($("#file1").val().length > 0) {                    ajaxFileUpload();                }                else {                    alert("請選擇圖片");                }            })        })        function ajaxFileUpload() {            $.ajaxFileUpload            (                {                    url: '/Home/Upload', //用於檔案上傳的伺服器端請求地址                    secureuri: false, //一般設定為false                    fileElementId: 'file1', //檔案上傳空間的id屬性  <input type="file" id="file" name="file" />                    dataType: 'HTML', //傳回值類型 一般設定為json                    success: function (data, status)  //伺服器成功響應處理函數                    {                        alert(data);                        $("#img1").attr("src", data);                        if (typeof (data.error) != 'undefined') {                            if (data.error != '') {                                alert(data.error);                            } else {                                alert(data.msg);                            }                        }                    },                    error: function (data, status, e)//伺服器響應失敗處理函數                    {                        alert(e);                    }                }            )            return false;        }    </script></head><body>    <p><input type="file" id="file1" name="file" /></p>    <input type="button" value="上傳" />    <p><img id="img1" alt="上傳成功啦" src="" /></p></body></html>
最後再來一個上傳圖片且附帶參數的執行個體:控制器代碼:
public class HomeController : Controller    {        public ActionResult Index()        {            return View();        }        public ActionResult Upload()        {            NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;            string imgPath = "";            if (hfc.Count > 0)            {                imgPath = "/testUpload" + hfc[0].FileName;                string PhysicalPath = Server.MapPath(imgPath);                hfc[0].SaveAs(PhysicalPath);            }            //注意要寫好後面的第二第三個參數            return Json(new { Id = nvc.Get("Id"), name = nvc.Get("name"), imgPath1 = imgPath },"text/html", JsonRequestBehavior.AllowGet);        }    }
Index視圖代碼:
<html><head>    <script src="/jquery-1.7.1.js" type="text/javascript"></script>    <script src="/ajaxfileupload.js" type="text/javascript"></script>    <script type="text/javascript">        $(function () {            $(":button").click(function () {                if ($("#file1").val().length > 0) {                    ajaxFileUpload();                }                else {                    alert("請選擇圖片");                }            })        })        function ajaxFileUpload() {            $.ajaxFileUpload            (                {                    url: '/Home/Upload', //用於檔案上傳的伺服器端請求地址                    type: 'post',                    data: { Id: '123', name: 'lunis' }, //此參數非常嚴謹,寫錯一個引號都不行                    secureuri: false, //一般設定為false                    fileElementId: 'file1', //檔案上傳空間的id屬性  <input type="file" id="file" name="file" />                    dataType: 'json', //傳回值類型 一般設定為json                    success: function (data, status)  //伺服器成功響應處理函數                    {                        alert(data);                        $("#img1").attr("src", data.imgPath1);                        alert("你請求的Id是" + data.Id + "     " + "你請求的名字是:" + data.name);                        if (typeof (data.error) != 'undefined') {                            if (data.error != '') {                                alert(data.error);                            } else {                                alert(data.msg);                            }                        }                    },                    error: function (data, status, e)//伺服器響應失敗處理函數                    {                        alert(e);                    }                }            )            return false;        }    </script></head><body>    <p><input type="file" id="file1" name="file" /></p>    <input type="button" value="上傳" />    <p><img id="img1" alt="上傳成功啦" src="" /></p></body></html>
此執行個體在顯示出非同步上傳圖片的同時並彈出自訂傳輸的參數。
  2013年1月28日,今天調試過程中發現一個問題,就是作為檔案域(<input type="file">)必須要有name屬性,如果沒有name屬性,上傳之後伺服器是擷取不到圖片的。如:正確的寫法是<input type="file" id="file1" name="file1" />
  2013年1月28日,最經典的錯誤終於找到原因所在了。Object function (a,b){return new e.fn.init(a,b,h)} has no method 'handleError',這個是google瀏覽器報的錯誤,非常經典, 不知道是我的版本問題還是真正存在的問題。這個問題的根源經過N次上傳才找到問題的根本所在。答案是:dataType參數一定要大寫。如:dataType: 'HTML'。
  2016-07-28,評論中的一個錯誤:TypeError: $.ajaxFileUpload is not a function 我們用的不是同一個JS,你下了別的AJAXFileUpload去了。

轉載地址:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.