簡體   English   中英

進度條顯示不正確的百分比

[英]progress bar showing incorrect percentage

我遵循了有關如何使用 js 使用 django 實現文件上傳進度條的教程,但問題是進度條在文件完成上傳我的 uploader.js 之前達到 100%

    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 新手,我不明白為什么這個函數給我的百分比比上傳文件所需的時間小得多

您可以使用 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM