温馨提示×

php file函数怎样处理大文件上传

PHP
小樊
81
2024-10-14 02:39:50
栏目: 编程语言

在PHP中,处理大文件上传时,可以使用以下方法:

  1. 修改PHP配置文件(php.ini):

    在php.ini文件中,设置以下选项以允许大文件上传:

    upload_max_filesize = 100M
    post_max_size = 100M
    memory_limit = 256M
    max_execution_time = 300
    

    这些设置分别表示:

    • upload_max_filesize:允许上传的最大文件大小(单位:MB)
    • post_max_size:POST请求中允许的最大数据量(单位:MB)
    • memory_limit:脚本允许使用的最大内存量(单位:MB)
    • max_execution_time:脚本允许的最大执行时间(单位:秒)

    修改这些值后,重启Web服务器以使更改生效。

  2. 使用分块上传:

    对于非常大的文件,可以将其分成多个较小的部分进行上传。这可以通过以下步骤实现:

    a. 在客户端,将文件分成多个较小的部分,并为每个部分分配一个唯一的标识符。

    b. 将这些部分发送到服务器,并在服务器端重新组合它们。

    以下是一个使用JavaScript和HTML实现分块上传的示例:

    <input type="file" id="fileInput" multiple>
    <button onclick="uploadChunks()">上传</button>
    
    <script>
        let uploadedChunks = [];
    
        function uploadChunks() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            const chunkSize = 1 * 1024 * 1024; // 1MB
            let start = 0;
    
            function uploadChunk() {
                const end = Math.min(start + chunkSize, file.size);
                const chunk = file.slice(start, end);
    
                const formData = new FormData();
                formData.append('file', chunk);
                formData.append('chunkIndex', start / chunkSize);
                formData.append('totalChunks', Math.ceil(file.size / chunkSize));
    
                fetch('/upload', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        uploadedChunks.push(data.chunkIndex);
                        start = end;
                        if (start < file.size) {
                            uploadChunk();
                        } else {
                            console.log('所有块都已上传');
                        }
                    } else {
                        console.error('上传失败');
                    }
                })
                .catch(error => {
                    console.error('上传错误:', error);
                });
            }
    
            uploadChunk();
        }
    </script>
    

    在服务器端,你需要创建一个名为upload的路由,用于处理文件块的上传。在这个路由中,你可以将文件块保存到临时目录,并在所有块上传完成后将它们合并为一个完整的文件。以下是一个简单的示例:

    <?php
    $targetDir = 'uploads/chunks/';
    $targetFile = 'uploads/complete_file.txt';
    $chunkIndex = isset($_POST['chunkIndex']) ? intval($_POST['chunkIndex']) : 0;
    $totalChunks = isset($_POST['totalChunks']) ? intval($_POST['totalChunks']) : 0;
    $chunkSize = 1 * 1024 * 1024; // 1MB
    
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }
    
    $tempFile = $targetDir . uniqid() . '.part';
    if (isset($_FILES['file'])) {
        move_uploaded_file($_FILES['file']['tmp_name'], $tempFile);
    }
    
    $file = fopen($tempFile, 'r');
    for ($i = 0; $i < $totalChunks; $i++) {
        $contents = fgets($file);
        $contents = trim($contents);
    
        if ($i === $chunkIndex) {
            $finalFile = fopen($targetFile, 'a');
            fwrite($finalFile, $contents);
            fclose($finalFile);
        }
    }
    
    fclose($file);
    unlink($tempFile);
    
    echo json_encode(['success' => true]);
    ?>
    

    这个示例中,我们将每个文件块保存到一个名为uploads/chunks/的临时目录中,并在所有块上传完成后将它们合并为一个名为uploads/complete_file.txt的完整文件。

0