1. 程式人生 > >純H5 AJAX檔案上傳加進度條功能

純H5 AJAX檔案上傳加進度條功能


上傳程式碼js部分


 //包上傳
    $('.up_apk').change(function () {
        var obj = $(this);
        var form_data = new FormData();
        // 獲取檔案
        var file_data = obj.prop("files")[0];
        // 表單資訊
        form_data.append("id", "001");
        form_data.append("name", "test");
        form_data.append("apk", file_data);
        if (file_data.type != 'application/vnd.android.package-archive') {
            alert('檔案格式錯誤');
            return false;
        }
        $('.jdt').slideDown('fast');
        var size = Math.round(file_data.size / 1024 / 1024 * 100) / 100 + 'MB';
        $('.jdt .size').html(size);
        //提交
        $.ajax({
            type: "POST",
            url: 'url',
            dataType: "json",
            processData: false, // 注意:讓jQuery不要處理資料
            contentType: false, // 注意:讓jQuery不要設定contentType
            data: form_data,

            xhr: function () { //獲取ajaxSettings中的xhr物件,為它的upload屬性繫結progress事件的處理函式  
                myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) { //檢查upload屬性是否存在  
                    //繫結progress事件的回撥函式  
                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                }
                return myXhr; //xhr物件返回給jQuery使用  
            },

            success: function (d) {
                if (d.code == 200) {
                    //處理返回資訊
                } else {
                    alert(d.msg);
                }
                $('.jdt').slideUp('slow');
            },
            error: function (e) {
                alert("錯誤!!");
            }
        });
        function progressHandlingFunction(e) {
            var curr = e.loaded;
            var total = e.total;
            var wan = Math.round(curr / 1024 / 1024 * 100) / 100;
            var bfb = Math.round(curr / total * 10000) / 100;
            $('.jdt .wan').html(wan + 'MB');
            $('.jdt .bfb').html(bfb + '%');
            $('.jdt .jindu').css('width', bfb + '%');
        }

    });


html部分


<style>
    .jdt{display: none;}
    .jdtjd{width: 500px;height: 15px;margin: 20px 0;border:1px solid #0a8c8b;border-radius: 7px;}
    .jdtcs{width: 500px;height: 10px;text-align: center;color:#006400;margin-top: -49px;}
    .jdt i{font-style:normal;}
    .jdtjd .jindu{display: block;height: 15px;width: 0%; border-radius: 7px; background-color: #00ccca;z-index: -1;}
    .jdtcs .bfb{text-align: center;}
    .jdtcs .size{float: right;}
    .jdtcs .wan{float:left;}
</style>
<input  class="up_apk" type="file" value="本地上傳" accept=".apk"/>                            
<div class="jdt">
      <div class="jdtjd"><i class="jindu"></i></div>
      <div class="jdtcs"><i class="wan">0MB</i><i class="bfb">0%</i><i class="size">0MB</i></div>
</div>