<!DOCTYPE html>
<html>
<head>
  <title>文件上传</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <input type="file" id="fileInput" multiple>
  <button id="uploadButton">上传</button>
  <div id="progressBar" style="display:none">
    <div id="progress"></div>
  </div>
  <div id="status"></div>
  <script>
    $(document).ready(function() {
      $('#uploadButton').click(function() {
        var files = $('#fileInput').get(0).files;
        if (files.length > 0) {
          var formData = new FormData();

          for (var i = 0; i < files.length; i++) {
            formData.append('files[]', files[i]);
          }

          $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            xhr: function() {
              var xhr = new window.XMLHttpRequest();
              xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                  var percent = Math.round((e.loaded / e.total) * 100);
                  $('#progress').css('width', percent + '%');
                }
              });
              return xhr;
            },
            beforeSend: function() {
              $('#progressBar').show();
              $('#status').empty().text('上传中...');
            },
            success: function(response) {
              $('#status').empty().text(response);
            },
            complete: function() {
              $('#progressBar').hide();
            }
          });
        }
      });
    });
  </script>
</body>
</html>
<?php
if(isset($_FILES['files'])){  $errors= array();  $file_name = $_FILES['files']['name'];  $file_size =$_FILES['files']['size'];  $file_tmp =$_FILES['files']['tmp_name'];  $file_type=$_FILES['files']['type'];  $file_ext=strtolower(end(explode('.',$_FILES['files']['name'])));  $extensions= array("jpeg","jpg","png");  if(in_array($file_ext,$extensions)=== false){     $errors[]="扩展名不允许,请选择 JPEG 或 PNG 文件。";  }  if($file_size > 2097152){     $errors[]='文件大小超过 2MB 的限制。';  }  if(empty($errors)==true){     move_uploaded_file($file_tmp,"uploads/".$file_name);     echo "文件上传成功。";  }else{     print_r($errors);  } } ?>

原文地址: https://www.cveoy.top/t/topic/p4tB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录