【问题标题】:progress bar showing incorrect percentage进度条显示不正确的百分比
【发布时间】:2021-01-31 10:40:59
【问题描述】:

我遵循了一个关于如何使用 django 使用 js 实现文件上传进度条的教程 但问题是在文件完成上传之前进度条已达到 100% 这是我的 uploader.js

    function check_ex() {
  var fullPath  = document.getElementById("id_video").value;
  if (fullPath) {
    var startIndex =
      fullPath.indexOf("\\") >= 0
        ? fullPath.lastIndexOf("\\")
        : fullPath.lastIndexOf("/");
    var filename = fullPath.substring(startIndex);
    if (filename.indexOf("\\") === 0 || filename.indexOf("/") === 0) {
      filename = filename.substring(1);
    }
    var x = filename.split('.').pop();
    if (x != 'mp4') {
      alert(x +' format is not allowed in video input, use only (mp4) extensions');
      location.reload()
    };
    
  }
}

$(document).ready(function () {
  $("form").on("submit", function (event) {
    event.preventDefault();
    check_ex();
    var formData = new FormData($("form")[0]);
    $.ajax({
      xhr: function () {
        var xhr = new window.XMLHttpRequest();
        xhr.upload.addEventListener("progress", function (e) {
          if (e.lengthComputable) {
            document.getElementById("loading_btn").classList.remove("d-none");
            document.getElementById("save_btn").classList.add("d-none");
            document.getElementById("progressdiv").classList.remove("d-none");

            var percent = Math.round((e.loaded / e.total) * 100);
            if (percent == 100) {
              document.getElementById("message_button").click();
            }

            $("#progressbar")
              .attr("aria-valuenow", percent)
              .css("width", percent + "%")
              .text(percent + " %");
          }
        });
        return xhr;
      },
      type: "POST",
      data: formData,
      processData: false,
      contentType: false,
      seccess: function () {},
    });
  });
});

我是 javascript 的新手,我不明白为什么这个函数给我的百分比与文件上传所需的时间相比要小得多

【问题讨论】:

    标签: javascript django ajax progress-bar


    【解决方案1】:

    您可以使用 aws-sdk 做到这一点。

    //app.js
    
    var bucket = new AWS.S3({
    //you need to reimplement this to hide your credentials in production, use environment variales or aws cognito identitiy
      accessKeyId: "YourAccessKey",
      secretAccessKey: "YourSecretAccessKey",
      //sessionToken: "SESSION_TOKEN", // optional you can remove if you don't want pass
      region: 'us-east-2'
     });
    
    uploadfile = function(fileName, file, folderName) {
      const params = {
        Bucket: "YourBucket Name Here",
        Key: folderName + fileName,
        Body: file,
        ContentType: file.type
      };
      return this.bucket.upload(params, function(err, data) {
        if (err) {
          console.log('There was an error uploading your file: ', err);
          alert('There was an error uploading your file: ', err);
          return false;
        }
        console.log('Successfully uploaded file.', data);
        alert("Uploaded Successfully");
        return true;
      });
    }
    
    uploadSampleFile = function() {
      var progressDiv = document.getElementById("myProgress");
      progressDiv.style.display="block";
      var progressBar = document.getElementById("myBar");
      file = document.getElementById("myFile").files[0];
      console.log(file)
      let ext = file.name.split('.').pop();
      //check extension
      if(ext != 'mp4') {
        alert(ext +' format is not allowed in video input, use only mp4 files');
        location.reload();
        return false;
        }
    
      folderName = "devtest/";
      //uploaded file's name in the bucket/folder should be unique.. pick a way to make it unique otherwise target file will be overwritten
      // uniqueFileName = 'NotUniqueSampleFile'; 
      uniqueFileName = file.name;
      let fileUpload = {
        id: "",
        name: file.name,
        nameUpload: uniqueFileName,
        size: file.size,
        type: "",
        timeReference: 'Unknown',
        progressStatus: 0,
        displayName: file.name,
        status: 'Uploading..',
      }
    
      uploadfile(uniqueFileName, file, folderName)
        .on('httpUploadProgress', function(progress) {
          let progressPercentage = Math.round(progress.loaded / progress.total * 100);
          //console.log(progressPercentage);
          progressBar.style.width = progressPercentage + "%";
          if (progressPercentage < 100) {
            fileUpload.progressStatus = progressPercentage;
    
          } else if (progressPercentage == 100) {
            fileUpload.progressStatus = progressPercentage;
            fileUpload.status = "Uploaded";
          }
        })
    }
    /*styles.css*/
    
    body {
      background: white;
      padding: 20px;
      font-family: Sans-serif;
      color: #000;
    }
    #myProgress {
      width: 100%;
      background-color: grey;
    }
    
    #myBar {
      width: 1%;
      height: 30px;
      background-color: green;
    }
    
    #banner-message {
      background: #fff;
      border-radius: 4px;
      padding: 20px;
      font-size: 25px;
      text-align: center;
      transition: all 0.2s;
      margin: 0 auto;
      width: 300px;
    }
    
    button {
      background: #0084ff;
      border: none;
      border-radius: 5px;
      padding: 8px 14px;
      font-size: 15px;
      color: #fff;
    }
    
    #banner-message.alt {
      background: #0084ff;
      color: #fff;
      margin-top: 40px;
      width: 200px;
    }
    
    #banner-message.alt button {
      background: #fff;
      color: #000;
    }
    <!-- template.html-->
    
    <html>
    
      <head>
        <title>  Upload Progress Bar</title>
        <link rel="stylesheet" href="styles.css">
        <script src="https://sdk.amazonaws.com/js/aws-sdk-2.773.0.min.js"></script>
    
        <script src="app.js"></script>
      </head>
    
      <body>
        <input type="file" id="myFile" multiple size="50" onchange="uploadSampleFile()">
    <br><br>
        <div id="myProgress" style="display:none;">
          <div id="myBar"></div>
        </div>
      </body>
    
    </html>

    【讨论】:

    • 非常感谢您的帮助,此方法非常有效,再次感谢我非常感谢您的帮助我的朋友@Youcef
    猜你喜欢
    • 1970-01-01
    • 2017-05-12
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2011-06-01
    相关资源
    最近更新 更多