PHP 上传、解压和进度条

2022-01-09 00:00:00 progress-bar upload php html

我需要帮助来为我的 php 上传网站创建进度条.我已经对上传和提取部分进行了排序,但我需要进度条方面的帮助.我不知道该怎么做.另外,上传文件是否有最大文件大小?

I need help with creating a progress bar for my php upload site. I've got the upload and exctract part sorted but i need help with the progress bar. I'm not sure how to do it. Also, is there a maximum file size for the upload?

HTML

<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose file (.zip): <input type="file" name="zip_file" /></label>
<br />
<input type="submit" value="Upload" name="submit" value="Upload" />
</form>

PHP

<?php
if($_FILES["zip_file"]["name"]) {
  $filename = $_FILES["zip_file"]["name"];
  $source = $_FILES["zip_file"]["tmp_name"];
  $type = $_FILES["zip_file"]["type"];

  $name = explode(".", $filename);
  $accepted_types = array(
    'application/zip', 
    'application/x-zip-compressed', 
    'multipart/x-zip', 
    'application/x-compressed');                          

  foreach($accepted_types as $mime_type) {
    if($mime_type == $type) {
      $okay = true;
      break;
    } 
  }

  $continue = strtolower($name[1]) == 'zip' ? true : false;
  if(!$continue) {
    $message = "[...] not a .zip file. Please try again.";
  }
  $target_path = "./".$filename;
  if(move_uploaded_file($source, $target_path)) {
    $zip = new ZipArchive();
    $x = $zip->open($target_path);
    if ($x === true) {
      $zip->extractTo("./");
      $zip->close();

      unlink($target_path);
    }
    $message = "Your .zip file was uploaded and unpacked.";
  } else {  
    $message = "There was a problem with the upload. Please try again.";
  }
}
?>

推荐答案

您可以进行一些更改以适应,但如果您想要一个进度条,这会很好.您可以添加更多事件侦听器并按照您的意愿进行操作.我希望这对你来说是一个很好的起点.

You can make some changes to fit but this works rather well if you want a progress bar. You can add more eventlisteners and make it how you want. I hope this is a good starting point for you.

function uploadFile(){
    var file = document.getElementById("zip_file").files[0];
    var formdata = new FormData();
    formdata.append("zip_file", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", function(event) { runprogress(event); } , false);
    ajax.addEventListener("load", function(event) {uploadcomplete(event); }, false);
    //Target your php file. 
    ajax.open("POST", "upload.php");
    ajax.send(formdata);
}
function runprogress(event){
    //The progress %, you might want to Math.round(percent) 
    var percent = (event.loaded / event.total) * 100;
}
function uploadcomplete(event){
    //This will = to your php reply.
    var AjaxReply=event.target.responseText;
}

相关文章