PHP simply implements file breakpoints and percentage uploads

 

 1. To implement PHP breakpoint upload, you can use the following steps:

  1. Create a file upload form on the front end with a file selection input and a submit button.
  2. Set the form's submit target to a PHP script that handles the file upload.
  3. In the PHP script, first check to see if there is a file uploaded, and if so, save the file to a temporary directory on the server.
  4. Get information about uploaded files, such as file name, file size, etc.
  5. Save file information to a database or other persistent storage for resumable uploads.
  6. On the front end, you can use JavaScript to monitor the upload progress of the file, and send the progress information to the back end.
  7. At the backend, update the file upload progress in the database according to the received progress information.
  8. If an interruption or error occurs during the upload process, the upload can be resumed according to the progress information in the database. It should be noted that uploading with breakpoints requires the uploading and merging of files in parts on the server side, as well as the monitoring of upload progress and the logic of resuming uploads at breakpoints at the front end. This involves complex operations such as file block processing, progress management, and file merging. Some third-party libraries or frameworks can be used to simplify the development process, such as Resumable.js, Dropzone.js, etc.

2. Create upload file 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. Upload the test.php file 

<?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. Upload successful display 

 

 

Guess you like

Origin blog.csdn.net/weixin_39934453/article/details/131923923