简体   繁体   中英

AJAX file upload progress bar in JavaScript

I have a working PHP script to upload files. To make it a bit fancier, I wanted to add a progress bar, but since I have no clue about anything in Javascript I watched this tutorial and everything seemed to work. When I choose a file and submit the form the progressbar gets from 0% to 100% but thats it. It just stucks at 100% and the file doesn't gets uploaded. (The upload script works perfectly fine without the "javascript progressbar script")

Javascript:

  const uploadForm = document.getElementById("uploadForm");
  const file = document.getElementById("file");
  const progressbarfill = document.querySelector("#upload_progressbar2 > .upload_progressbar-fill");
  const progressbartext = progressbarfill.querySelector(".upload_progressbar-text");

  uploadForm.addEventListener("submit", uploadFile);

  function uploadFile (e) {
    e.preventDefault();

    const xhr = new XMLHttpRequest();

    xhr.open("POST", "upload.php");
    xhr.upload.addEventListener("progress", e => {
      const percent = e.lengthComputable ? (e.loaded / e.total) * 100 : 0;

      progressbarfill.style.width = percent.toFixed(2) + "%";
      progressbartext.textContent = percent.toFixed(2) + "%";    
    });

    xhr.setRequestHeader("Content-Type", "multipart/form-data");
    xhr.send(new FormData(uploadForm));
  }

HTML:

<div class="card-body">
  <form method="POST" id="uploadForm" enctype="multipart/form-data">       
    <div class="value">
      <div class="input-group js-input-file">
        <input class="input-file" type="file" name="file" id="file">
        <label class="label--file" for="file"><i class="fas fa-search"></i>&nbsp; choose file</label>
        <span class="input-file__info">no file selected</span>
      </div>
    </div>
    <div class="card-footer">
      <div class="upload_progressbar" id="upload_progressbar2">
        <div class="upload_progressbar-fill">
          <span class="upload_progressbar-text">0%</span>
        </div>
      </div>
      <button type="submit" class="btn btn-block btn-outline-info btn-flat" name="upload_file">send</button>
    </div>
  </form>
</div>

PHP:

if (isset($_POST['upload_file'])) {
  $file = $_FILES['file'];

  $fileName = $_FILES['file']['name'];
  $fileTmpName = $_FILES['file']['tmp_name'];
  $fileSize = $_FILES['file']['size'];
  $fileError = $_FILES['file']['error'];
  $fileType = $_FILES['file']['type'];
  $file_user = $_SESSION['auth']['username'];

  $fileExt = explode('.', $fileName);
  $fileActualExt = strtolower(end($fileExt));

  $allowed = array('jpg', 'jpeg', 'png', "psd", "rar", "zip", "flp", "mp3", "wav", "m4a", "mp4");

  if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
                $fileNameNew = uniqid('', true).".".$fileActualExt;
                $fileDestination = 'uploads/'.$fileNameNew;

                $cnx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $insert_query = "INSERT INTO uploads (uploaded, username, new_name, old_name, type, size) VALUES (now(), ?, ?, ?, ?, ?)";
                $insert = $cnx->prepare($insert_query);
                $insert->execute(array($file_user, $fileNameNew, $fileName, $fileActualExt, $fileSize));

                move_uploaded_file($fileTmpName, $fileDestination);
                header("Location: upload?success");
        } else {
          $_SESSION['flash']['danger'] = "xxxx";
                header("Location: upload.php");
                exit();
        }
  } else {
    $_SESSION['flash']['danger'] = "xxx";
          header("Location: upload.php");
          exit();
  }
}

Thanks in advance for any help and sorry for typos (english is not my native language)

I think you are missing loadend event - try this resource for more help https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/loadend_event .

And for similar full working example, you can check this post - JavaScript loading progress of an image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM