FormDataアップロードファイルの進捗率を表示します.

2436 ワード





FormData           








var xhr = new XMLHttpRequest();
var progressBar = document.getElementById('upload_progress');
$('#btn_start').click(function() {
    var uploadFile = document.getElementById('upload_file').files[0];
    var formData = new FormData();
    formData.append('upload_file', uploadFile);

    // ---------------------------------------
    //   xmlHttpRequest  
    xhr.open('post', '/server_url.php');
    xhr.onload = function() {
        alert('  !');
    };
    xhr.onerror = function() {
        alert('       !');
    };
    xhr.upload.onprogress = function(progress) {
        if (progress.lengthComputable) {
            console.log(progress.loaded / progress.total * 100);
            progressBar.max = progress.total;
            progressBar.value = progress.loaded;
        }
    };
    xhr.upload.onloadstart = function() {
        console.log('started...');
    };
    xhr.send(formData);

    // ---------------------------------------
    //   jQuery  
    /**
    $.ajax({
       type: "POST",
      url: "/server_url.php",
      data: formData , //          formData   
      processData: false, 
      contentType: false, //  false         Content-Type
      //       jQuery    XMLHttpRequest  ,     progress     ,       ajax  
      xhr: function() {
        var xhr = $.ajaxSettings.xhr();
        if (xhr.upload) {
          xhr.upload.onprogress = function(progress) {
                    if (progress.lengthComputable) {
                        console.log(progress.loaded / progress.total * 100);
                        progressBar.max = progress.total;
                        progressBar.value = progress.loaded;
                    }
                };
                xhr.upload.onloadstart = function() {
                    console.log('started...');
                };
         }
              return xhr;
       }
    }).done(function(resp) {
        alert('  !');
    }).fail(function(err) {
        alert('       !')
    });*/

});

$('#btn_cancel').click(function() {
    xhr.abort();
});