jquery+ajax實現非同步上傳檔案顯示進度條
阿新 • • 發佈:2020-08-18
前言:
今天專案中加了一個上傳檔案加進度條的需求,我就搞了一下。時間寶貴不多說,直接進入正題。
非同步上傳檔案是要用到ajax裡的一個小的知識點:xhr(XML Http Request)一個物件,xhr物件也是ajax一個核心。
關於使用它也很簡單:就四步(下面這樣寫也可以向後端進行傳送請求)
var xhr=new XMLHttpRequest()//建立xhr物件 xhr.open('請求方式','請求的地址') xhr.send()//發佛那個請求 xhr.onreadystatechange=function(){ if (xhr.readyState==4){//得到服務端返回的狀態碼 console.log(xhr.responseText)//輸出返回結果 } }
介紹完xhr繼續說上傳檔案的:(注意:在展示效果的時候,有一個知識點,就是css樣式,一定要在新增的在之前,否則當三上傳的檔案較小的時候,會不顯示效果)
//上傳檔案 $("#btnSubmit").click(function () { if (!(confirm("確定提交嗎?"))) { return; } else { var formData = new FormData();//上傳檔案必須寫的 var fileNum = $("#file_input")[0].files.length;//上傳檔案的個數 if (fileNum > 0) { var file = $("#file_input")[0].files;//拿到檔案 //console.log(file[0].name);檔名 var nameSuffix = file[0].name.split("."); if (nameSuffix[nameSuffix.length - 1] != "zip") { alert("上傳的檔案不是zip型別的檔案,請重新上傳"); $("#file_input").val("");//將選擇的檔案清除 }//判斷檔案大小 //else if ($("#file_input")[0].files[0].size / 1024 / 1024 > 1024) { //alert("請選擇檔案大小為1G以內檔案"); //$("#file_input").val(""); //return; //} else { //formData.append(key,value)的值不能一樣,否則只會拿到一個檔案 formData.append('file',file[0]);//拿到zip檔案 //console.log(formData.get('file'));檢視新增到formData的檔案 } $.ajax({ url: 'https://www.baidu.com',//用百度測試的。哈哈 type: 'post',async:true,//這裡要設定非同步上傳,才能成功呼叫myXhr.upload.addEventListener('progress',function(e){}),progress的回掉函式 dataType: 'json',//Accept:'text/html;charset=UTF-8',processData: false,// 告訴jQuery不要去處理髮送的資料 contentType: false,// 告訴jQuery不要去設定Content-Type請求頭,否則後端拿不到資料 data: formData,xhr:function(){ var myXhr = $.ajaxSettings.xhr(); if(myXhr.upload){ //檢查上傳的檔案是否存在 myXhr.upload.addEventListener('progress',function(e){ var loaded = e.loaded; //已經上傳大小情況 var total = e.total; //附件總大小 var percent = Math.floor(100*loaded/total)+"%"; //已經上傳的百分比 //console.log("已經上傳了:"+percent); //顯示進度條 $("#content").css("width",percent).css("height",20).css("margin-top",8).css("backgroundColor","#33CCFF").css("color","white").html(""+percent+""); },false); // for handling the progress of the upload } return myXhr; },success:function(data){ alert("上傳成功!!!!"); },error:function(){ alert("上傳失敗!"); //上傳失敗後清空div的樣式和內容 $("#content").css("width",0).css("height",0).css("margin-top",0).css("backgroundColor","").text(""); } }) } else { alert("請選擇檔案上傳"); } } })
效果展示:
更多精彩內容請參考專題《ajax上傳技術彙總》,《javascript檔案上傳操作彙總》和《jQuery上傳操作彙總》進行學習。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。