php file函數(shù)怎樣處理大文件上傳

PHP
小樊
81
2024-10-14 02:39:50

在PHP中,處理大文件上傳時(shí),可以使用以下方法:

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

    在php.ini文件中,設(shè)置以下選項(xiàng)以允許大文件上傳:

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

    這些設(shè)置分別表示:

    • upload_max_filesize:允許上傳的最大文件大?。▎挝唬篗B)
    • post_max_size:POST請(qǐng)求中允許的最大數(shù)據(jù)量(單位:MB)
    • memory_limit:腳本允許使用的最大內(nèi)存量(單位:MB)
    • max_execution_time:腳本允許的最大執(zhí)行時(shí)間(單位:秒)

    修改這些值后,重啟Web服務(wù)器以使更改生效。

  2. 使用分塊上傳:

    對(duì)于非常大的文件,可以將其分成多個(gè)較小的部分進(jìn)行上傳。這可以通過(guò)以下步驟實(shí)現(xiàn):

    a. 在客戶(hù)端,將文件分成多個(gè)較小的部分,并為每個(gè)部分分配一個(gè)唯一的標(biāo)識(shí)符。

    b. 將這些部分發(fā)送到服務(wù)器,并在服務(wù)器端重新組合它們。

    以下是一個(gè)使用JavaScript和HTML實(shí)現(xiàn)分塊上傳的示例:

    <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('上傳錯(cuò)誤:', error);
                });
            }
    
            uploadChunk();
        }
    </script>
    

    在服務(wù)器端,你需要?jiǎng)?chuàng)建一個(gè)名為upload的路由,用于處理文件塊的上傳。在這個(gè)路由中,你可以將文件塊保存到臨時(shí)目錄,并在所有塊上傳完成后將它們合并為一個(gè)完整的文件。以下是一個(gè)簡(jiǎn)單的示例:

    <?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]);
    ?>
    

    這個(gè)示例中,我們將每個(gè)文件塊保存到一個(gè)名為uploads/chunks/的臨時(shí)目錄中,并在所有塊上傳完成后將它們合并為一個(gè)名為uploads/complete_file.txt的完整文件。

0