五月综合缴情婷婷六月,色94色欧美sute亚洲线路二,日韩制服国产精品一区,色噜噜一区二区三区,香港三级午夜理伦三级三

您現(xiàn)在的位置: 365建站網(wǎng) > 365文章 > jQuery插件之a(chǎn)jaxFileUpload上傳文件的方法

jQuery插件之a(chǎn)jaxFileUpload上傳文件的方法

文章來(lái)源:365jz.com     點(diǎn)擊數(shù):288    更新時(shí)間:2017-12-07 09:09   參與評(píng)論
ajaxFileUpload.js 很多同名的,因?yàn)樽龀鰜?lái)一個(gè)很容易。

我用的是這個(gè):https://github.com/carlcarl/AjaxFileUpload

下載地址在這里:http://files.cnblogs.com/files/kissdodog/ajaxfileupload_JS_File.rar

AjaxFileUpload.js并不是一個(gè)很出名的插件,只是別人寫好的放出來(lái)供大家用,原理都是創(chuàng)建隱藏的表單和iframe然后用JS去提交,獲得返回值。

當(dāng)初做了個(gè)異步上傳的功能,選擇它因?yàn)樗呐渲梅绞奖容^像jQuery的AJAX,我很喜歡。

評(píng)論里面說(shuō)到的不行。那是因?yàn)槲覀冇玫牟皇峭粋€(gè)js。我上github搜AjaxFileUpload出來(lái)很多類似js。

ajaxFileUpload是一個(gè)異步上傳文件的jQuery插件

  傳一個(gè)不知道什么版本的上來(lái),以后不用到處找了。

  語(yǔ)法:$.ajaxFileUpload([options])

  options參數(shù)說(shuō)明:

1、url            上傳處理程序地址?! ?br /> 2,fileElementId       需要上傳的文件域的ID,即<input type="file">的ID。
3,secureuri        是否啟用安全提交,默認(rèn)為false。
4,dataType        服務(wù)器返回的數(shù)據(jù)類型??梢詾閤ml,script,json,html。如果不填寫,jQuery會(huì)自動(dòng)判斷。
5,success        提交成功后自動(dòng)執(zhí)行的處理函數(shù),參數(shù)data就是服務(wù)器返回的數(shù)據(jù)。
6,error          提交失敗自動(dòng)執(zhí)行的處理函數(shù)。
7,data           自定義參數(shù)。這個(gè)東西比較有用,當(dāng)有數(shù)據(jù)是與上傳的圖片相關(guān)的時(shí)候,這個(gè)東西就要用到了。
8, type            當(dāng)要提交自定義參數(shù)時(shí),這個(gè)參數(shù)要設(shè)置成post

錯(cuò)誤提示:

1,SyntaxError: missing ; before statement錯(cuò)誤
  如果出現(xiàn)這個(gè)錯(cuò)誤就需要檢查url路徑是否可以訪問(wèn)
2,SyntaxError: syntax error錯(cuò)誤
  如果出現(xiàn)這個(gè)錯(cuò)誤就需要檢查處理提交操作的服務(wù)器后臺(tái)處理程序是否存在語(yǔ)法錯(cuò)誤
3,SyntaxError: invalid property id錯(cuò)誤
  如果出現(xiàn)這個(gè)錯(cuò)誤就需要檢查文本域?qū)傩訧D是否存在
4,SyntaxError: missing } in XML expression錯(cuò)誤
  如果出現(xiàn)這個(gè)錯(cuò)誤就需要檢查文件name是否一致或不存在
5,其它自定義錯(cuò)誤
  大家可使用變量$error直接打印的方法檢查各參數(shù)是否正確,比起上面這些無(wú)效的錯(cuò)誤提示還是方便很多。



  使用方法:

  第一步:先引入jQuery與ajaxFileUpload插件。注意先后順序,這個(gè)不用說(shuō)了,所有的插件都是這樣。

    <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', //用于文件上傳的服務(wù)器端請(qǐng)求地址
                    secureuri: false, //是否需要安全協(xié)議,一般設(shè)置為false
                    fileElementId: 'file1', //文件上傳域的ID
                    dataType: 'json', //返回值類型 一般設(shè)置為json
                    success: function (data, status)  //服務(wù)器成功響應(yīng)處理函數(shù)
                    {
                        $("#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)//服務(wù)器響應(yīng)失敗處理函數(shù)
                    {
                        alert(e);
                    }
                }
            )
            return false;
        }
    </script>


    第四步:后臺(tái)頁(yè)面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();
            }
        }


來(lái)一個(gè)MVC版本的實(shí)例:

控制器代碼

    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代碼,成功上傳后,返回圖片真實(shí)地址并綁定到<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("請(qǐng)選擇圖片");
                }
            })
        })
        function ajaxFileUpload() {
            $.ajaxFileUpload
            (
                {
                    url: '/Home/Upload', //用于文件上傳的服務(wù)器端請(qǐng)求地址
                    secureuri: false, //一般設(shè)置為false
                    fileElementId: 'file1', //文件上傳空間的id屬性  <input type="file" id="file" name="file" />
                    dataType: 'HTML', //返回值類型 一般設(shè)置為json
                    success: function (data, status)  //服務(wù)器成功響應(yīng)處理函數(shù)
                    {
                        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)//服務(wù)器響應(yīng)失敗處理函數(shù)
                    {
                        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>


最后再來(lái)一個(gè)上傳圖片且附帶參數(shù)的實(shí)例:控制器代碼:

    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);
            }
            //注意要寫好后面的第二第三個(gè)參數(shù)
            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("請(qǐng)選擇圖片");
                }
            })
        })
        function ajaxFileUpload() {
            $.ajaxFileUpload
            (
                {
                    url: '/Home/Upload', //用于文件上傳的服務(wù)器端請(qǐng)求地址
                    type: 'post',
                    data: { Id: '123', name: 'lunis' }, //此參數(shù)非常嚴(yán)謹(jǐn),寫錯(cuò)一個(gè)引號(hào)都不行
                    secureuri: false, //一般設(shè)置為false
                    fileElementId: 'file1', //文件上傳空間的id屬性  <input type="file" id="file" name="file" />
                    dataType: 'json', //返回值類型 一般設(shè)置為json
                    success: function (data, status)  //服務(wù)器成功響應(yīng)處理函數(shù)
                    {
                        alert(data);
                        $("#img1").attr("src", data.imgPath1);
                        alert("你請(qǐng)求的Id是" + data.Id + "     " + "你請(qǐng)求的名字是:" + data.name);
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert(data.msg);
                            }
                        }
                    },
                    error: function (data, status, e)//服務(wù)器響應(yīng)失敗處理函數(shù)
                    {
                        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>


此實(shí)例在顯示出異步上傳圖片的同時(shí)并彈出自定義傳輸?shù)膮?shù)。本實(shí)例下載地址

  2013年1月28日,今天調(diào)試過(guò)程中發(fā)現(xiàn)一個(gè)問(wèn)題,就是作為文件域(<input type="file">)必須要有name屬性,如果沒(méi)有name屬性,上傳之后服務(wù)器是獲取不到圖片的。如:正確的寫法是<input type="file" id="file1" name="file1" />

  2013年1月28日,最經(jīng)典的錯(cuò)誤終于找到原因所在了。Object function (a,b){return new e.fn.init(a,b,h)} has no method 'handleError',這個(gè)是google瀏覽器報(bào)的錯(cuò)誤,非常經(jīng)典, 不知道是我的版本問(wèn)題還是真正存在的問(wèn)題。這個(gè)問(wèn)題的根源經(jīng)過(guò)N次上傳才找到問(wèn)題的根本所在。答案是:dataType參數(shù)一定要大寫。如:dataType: 'HTML'。

  2016-07-28,評(píng)論中的一個(gè)錯(cuò)誤:TypeError: $.ajaxFileUpload is not a function   我們用的不是同一個(gè)JS,你下了別的AJAXFileUpload去了。
示例代碼:

=====================upload.html=======================

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ajaxfileupload圖片上傳控件</title>
</head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
<script type="text/javascript" src="http://www.phpletter.com/contents/ajaxfileupload/ajaxfileupload.js"></script>
<script language="javascript">
  jQuery(function(){  
      $("#buttonUpload").click(function(){    
         //加載圖標(biāo)  
         /* $("#loading").ajaxStart(function(){
            $(this).show();
         }).ajaxComplete(function(){
            $(this).hide();
         });*/
          //上傳文件
        $.ajaxFileUpload({
            url:'upload.php',//處理圖片腳本
            secureuri :false,
            fileElementId :'fileToUpload',//file控件id
            dataType : 'json',
            success : function (data, status){
                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>


<body>
<input id="fileToUpload" type="file" size="20" name="fileToUpload" class="input">
<button id="buttonUpload">上傳</button>
<!--<img id="loading" src="loading.jpg" style="display:none;">-->
</body>
</html>


=====================upload.php=======================

$res["error"] = "";//錯(cuò)誤信息
$res["msg"] = "";//提示信息
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'],"c:\\test.jpg")){
    $res["msg"] = "ok";
}else{
    $res["error"] = "error";
}
echo json_encode($res);

如對(duì)本文有疑問(wèn),請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答??! 點(diǎn)擊進(jìn)入論壇

發(fā)表評(píng)論 (288人查看0條評(píng)論)
請(qǐng)自覺(jué)遵守互聯(lián)網(wǎng)相關(guān)的政策法規(guī),嚴(yán)禁發(fā)布色情、暴力、反動(dòng)的言論。
昵稱:
最新評(píng)論
------分隔線----------------------------

其它欄目

· 建站教程
· 365學(xué)習(xí)

業(yè)務(wù)咨詢

· 技術(shù)支持
· 服務(wù)時(shí)間:9:00-18:00
365建站網(wǎng)二維碼

Powered by 365建站網(wǎng) RSS地圖 HTML地圖

copyright © 2013-2024 版權(quán)所有 鄂ICP備17013400號(hào)