PHP는 단순히 파일 중단점과 백분율 업로드를 구현합니다.

 

 1. PHP 중단점 업로드를 구현하려면 다음 단계를 사용할 수 있습니다.

  1. 파일 선택 입력 및 제출 버튼이 있는 프런트 엔드에 파일 업로드 양식을 만듭니다.
  2. 양식의 제출 대상을 파일 업로드를 처리하는 PHP 스크립트로 설정합니다.
  3. PHP 스크립트에서 먼저 업로드된 파일이 있는지 확인하고, 있다면 파일을 서버의 임시 디렉터리에 저장합니다.
  4. 파일 이름, 파일 크기 등과 같은 업로드된 파일에 대한 정보를 가져옵니다.
  5. 재개 가능한 업로드를 위해 파일 정보를 데이터베이스 또는 기타 영구 저장소에 저장합니다.
  6. 프런트 엔드에서 JavaScript를 사용하여 파일의 업로드 진행 상황을 모니터링하고 진행 정보를 백엔드로 보낼 수 있습니다.
  7. 백엔드에서 수신된 진행 정보에 따라 데이터베이스의 파일 업로드 진행을 업데이트합니다.
  8. 업로드 과정에서 중단이나 오류가 발생하면 데이터베이스의 진행 정보에 따라 업로드를 재개할 수 있습니다. 중단점을 사용하여 업로드하려면 서버 측에서 부분적으로 파일을 업로드하고 병합해야 하며 업로드 진행 상황을 모니터링하고 프런트 엔드의 중단점에서 업로드를 재개하는 논리가 필요합니다. 여기에는 파일 블록 처리, 진행 관리 및 파일 병합과 같은 복잡한 작업이 포함됩니다. Resumable.js, Dropzone.js 등과 같은 일부 타사 라이브러리 또는 프레임워크를 사용하여 개발 프로세스를 단순화할 수 있습니다.

2. 업로드 파일 html 생성 

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
    <title>文件断点上传</title>
    <style>
        #progressWrapper {
            display: flex;
            align-items: center;
        }
        #progressBar {
            flex: 1;
            margin-right: 10px;
        }
    </style>
</head>
<body>
<h1>文件断点上传示例</h1>
<input type="file" id="fileInput">
<button onclick="upload()">上传</button>
<div id="progressWrapper">
    <span id="progressPercentage">0%</span>
    <progress id="progressBar" value="0" max="100"></progress>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
    var chunkSize = 1024 * 1024; // 1MB
    var progressBar = document.getElementById('progressBar');
    var progressPercentage = document.getElementById('progressPercentage');
    function upload() {
        var fileInput = document.getElementById('fileInput');
        var file = fileInput.files[0];
        if (file) {
            uploadFile(file);
        }
    }
    function uploadFile(file) {
        var start = 0;
        var end = chunkSize;
        var totalSize = file.size;
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'test.php', true);
        // 上传进度事件
        xhr.upload.addEventListener('progress', function(event) {
            if (event.lengthComputable) {
                var percent = (event.loaded / event.total) * 100;
                progressBar.value = percent;
                progressPercentage.textContent = percent.toFixed(2) + '%';
            }
        });
        xhr.onreadystatechange = function() {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                if (xhr.status === 200) {
                    var receivedBytes = parseInt(xhr.responseText);
                    if (receivedBytes < totalSize) {
                        start = receivedBytes;
                        end = start + chunkSize;
                        uploadNextChunk();
                    } else {
                        alert('文件上传成功!');
                    }
                } else {
                    alert('上传失败,错误码:' + xhr.status);
                }
            }
        };
        function uploadNextChunk() {
            var chunk = file.slice(start, end);
            var formData = new FormData();
            formData.append('chunk', chunk);
            formData.append('start', start);
            formData.append('file', file);
            xhr.send(formData);
        }
        uploadNextChunk();
    }
</script>
</body>
</html>

3. test.php 파일 업로드 

<?php

$targetDir = "./uploads/"; // 文件保存目录,确保该目录存在并可写
$chunkSize = 1024 * 1024; // 1MB
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["chunk"]) && isset($_POST["start"])) {
    $chunk = $_FILES["chunk"];
    $files = $_FILES["file"];
    $start = intval($_POST["start"]);
    $fileName = $files["name"];
    $filePath = $targetDir . $fileName;
    // 获取已上传的总字节数
    $receivedBytes = 0;
    if (file_exists($filePath)) {
        $receivedBytes = filesize($filePath);
    }
    // 如果是第一个块,创建或覆盖目标文件
    if ($start === 0) {
        $file = fopen($filePath, "wb");
        if (!$file) {
            echo "无法打开文件";
            exit;
        }
    } else {
        // 如果不是第一个块,以追加的方式打开目标文件
        $file = fopen($filePath, "ab");
        if (!$file) {
            echo "无法打开文件";
            exit;
        }
        // 移动文件指针到已上传的位置
        fseek($file, $receivedBytes);
    }
    // 将块数据追加到目标文件
    if (fwrite($file, file_get_contents($chunk["tmp_name"])) === false) {
        echo "写入文件失败";
        exit;
    }
    // 关闭文件
    fclose($file);
    // 计算已上传的总字节数
    $receivedBytes += $chunk["size"];
    // 返回已上传的总字节数给客户端
    echo $receivedBytes;
}
?>

4. 성공적인 디스플레이 업로드 

 

 

추천

출처blog.csdn.net/weixin_39934453/article/details/131923923