0
votes

i followed a tutorial on how to implement a file upload progress bar with django using js but the problem is that the progress bar is reaching 100% before the file completed uploading this my 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 () {},
    });
  });
});

im new in javascript and i couldn't understand why this function is giving me so much smaller percentage comparing to the time that the file takes to upload

1

1 Answers

0
votes

you can do it this way using 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>