进度模式上传节点js ajax

时间:2017-04-19 14:06:35

标签: javascript jquery node.js ajax

我正在建立一个文档文件上传器。我想显示上传状态的百分比。

<div class="modal-body">
  <div class="container_upload" id="new_file_form">
    <div id="div_new_file_form" class="text-center" style="padding:2%;">
      <div class="form-group text-center">
        <input type="file" class="form-control" name="file_images"
          id="url_file" multiple="true" accept=".pdf,.doc,.xls,.ppt,.docx,.xlsx,.pptx"/>
      </div>      
      <button class="btn btn-success btn-lg" id="insert_btn">Carica</button>
      <br>
    </div>
  </div>
</div>

我使用 fileinput.js 来配置我的上传器:

$("#url_file").fileinput({
    language: 'it',
    showUpload: false,
    previewFileType:'any',
    maxFileCount: max_n_files,
    maxFileSize: maxsize/1000, //kB
    browseClass: "btn btn-primary",
    browseLabel: "Seleziona File",
    browseIcon: "<i class=\"glyphicon glyphicon-file\"></i> ",
    removeClass: "btn btn-danger",
    removeLabel: "Elimina",
    uploadClass: "btn btn-info",
    uploadUrl: "http://localhost/upload", 
    allowedFileExtensions: ["pdf", "doc", "xls", "ppt", "docx", "xlsx", "pptx"]
});

我使用ajax调用将文件发送到我的节点服务器,在那里处理文件。

$.ajax({
    beforeSend: showLoaderModal(),
    url: '/uploadFile',
    data: myFormData,
    processData: false,
    cache: false,
    contentType: false,
    type: 'POST',
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.upload.onprogress = function(e) {
            percentage = Math.floor(e.loaded / e.total *100) + '%';
            //$(".progress-bar").append(percentage);
            $(".progress-bar").empty();
            $(".progress-bar").append(percentage);
            $("progress-bar").attr("style","color: white;");
            //console.log(percentage);
            //console.log(percentage === "100%");

            $(".progress-bar").animate({
                width: percentage 
            }, 
            function() {
              upload_end = $(".progress-bar").css("width");
              console.log(upload_end);
              if(upload_end == "100%") {
                console.log("ci siamo");
                $(".end_upload").empty();
                $(".end_upload").append('Upload completato. Conversione file in corso... ');
              }
            });

            console.log(myFormData);          
        };

        return xhr;
    }

  }).done(function (msg, state) {
      hideLoaderModal();
      success_msg(msg);
      getMySize('size_disp');
      $("#url_file").fileinput('clear');

      if(msg.status == "DOCUMENT_UPLOADED"){
        $("#upload_modal").modal('toggle');
        //setTimeout(function(){ window.location.href ='/myFiles'; }, 2000);
      }

      $("#msg_booking").empty();
      $("#msg_no_file").empty();

      //call the getFiles function again for updating the list
      if(window.location.pathname === '/book') {
        get_myFiles(false);
      } 
      else if(window.location.pathname.toLowerCase() === '/myfiles') {
        getMyFiles();
      }

  }).fail(function (jqXHR, textStatus, errorThrown) {
    hideLoader();
    $("#upload_modal").modal('toggle');
    $("#url_file").fileinput('clear');
    getMySize('size_disp');

    if(window.location.pathname === '/book') {
      get_myFiles(false);
    } 
    else if(window.location.pathname.toLowerCase() === '/myfiles') {
      getMyFiles();
    }

    if(jqXHR.responseText) {
      msg = JSON.parse(jqXHR.responseText);
      error_msg(msg);
    } 
    else {
      error_msg(textStatus);
      //alert("An error occurred:\n" + textStatus);
    }
});

在我的节点js route 中,我将文件的信息放在我的数据库中,如果文件不是pdf格式,我将转换它。 所以,我的问题是: 如何跟踪上传执行的进度? 因为 xhr.upload.onpgrogress 在Ajax调用之前结束。

1 个答案:

答案 0 :(得分:0)

我认为您可能会错过使用Onchange以使您的进度条适用于此部分:

$(".progress-bar").animate({
                    width: percentage 
                }, function() {
                    upload_end = $(".progress-bar").css("width");
                    console.log(upload_end);
                    if(upload_end == "100%") {
                        console.log("ci siamo");
                        $(".end_upload").empty();
                        $(".end_upload").append('Upload completato. Conversione file in corso... ');
                    }
                });

你必须把你的ajax放在onchange函数中,然后调用ajax。请遵循此link并可能会帮助您

像这样:

$('.upload-btn').on('click', function (){
    $('#upload-input').click();
    $('.progress-bar').text('0%');
    $('.progress-bar').width('0%');
});

$('#upload-input').on('change', function(){

  var files = $(this).get(0).files;

  if (files.length > 0){
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();

    // loop through all the selected files and add them to the formData object
    for (var i = 0; i < files.length; i++) {
      var file = files[i];

      // add the files to formData object for the data payload
      formData.append('uploads[]', file, file.name);
    }

    $.ajax({
      url: '/upload',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data){
          console.log('upload successful!\n' + data);
      },
      xhr: function() {
        // create an XMLHttpRequest
        var xhr = new XMLHttpRequest();

        // listen to the 'progress' event
        xhr.upload.addEventListener('progress', function(evt) {

          if (evt.lengthComputable) {
            // calculate the percentage of upload completed
            var percentComplete = evt.loaded / evt.total;
            percentComplete = parseInt(percentComplete * 100);

            // update the Bootstrap progress bar with the new percentage
            $('.progress-bar').text(percentComplete + '%');
            $('.progress-bar').width(percentComplete + '%');

            // once the upload reaches 100%, set the progress bar text to done
            if (percentComplete === 100) {
              $('.progress-bar').html('Done');
            }

          }

        }, false);

        return xhr;
      }
    });

  }
});