jq ajax 上傳檔案 顯示進度
阿新 • • 發佈:2022-12-09
$('#uppic').change(function () { var files = $(this).prop('files'); if (!files.length) { upEnd() return; } upStart(); console.log(files); var data = new FormData(); data.append('pic', files[0]); $.ajax({ url: '/admin/fileupload/index', type: 'POST', data: data, cache: false, processData: false, contentType: false, xhr: function () { var xhr = new XMLHttpRequest(); //使用XMLHttpRequest.upload監聽上傳過程,註冊progress事件,列印回撥函式中的event事件 xhr.upload.addEventListener('progress', function (e) { console.log(e); //loaded代表上傳了多少 //total代表總數為多少 var progressRate = Math.round((e.loaded / e.total) * 100,-2) + '%'; $("#up_btn").text('上傳中,請稍後...'+progressRate) //通過設定進度條的寬度達到效果 // $('.progress > div').css('width', progressRate); }) xhr.upload.addEventListener('load', function (e) { console.log(e); //loaded代表上傳了多少 //total代表總數為多少 // var progressRate = Math.round((e.loaded / e.total) * 100,-2) + '%'; $("#up_btn").text('後臺處理中...') //通過設定進度條的寬度達到效果 // $('.progress > div').css('width', progressRate); }) return xhr; }, success: function (res) { console.log(res) upEnd() if (res.status == 'OK') { appendPic(res.data.url); } else { alert(res.msg); } } }); }); var input_index = typeof (updindex) != "undefined" ? updindex : 0; var upIng = false; function appendPic(_url) { input_index++; $("#pic_input_list").append("<input type=\"hidden\" id=\"pic_input_" + input_index + "\" name=\"pic[]\" value=\"" + _url + "\">") $("#pic_list").append("<li id=\"pic_" + input_index + "\"><img src=\"" + _url + "\"/> <div class=\"del_pic_btn\" onclick=\"delPic(" + input_index + ")\"> X </div> </li>") } $("#up_btn").click(function () { if (upIng) return false; $('#uppic').click(); }) function delPic(_index) { $("#pic_input_" + _index).remove(); $("#pic_" + _index).remove(); } function upStart() { upIng = true; $("#up_btn").text('上傳中,請稍後...') } function upEnd() { upIng = false; $("#up_btn").text('上傳圖片') }