当前位置: 首页 > news >正文

PHP处理大文件上传

前段HTML代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>分块上传大文件</title>
</head>
<body>
    <input type="file" id="fileInput">
    <button onclick="uploadFileInChunks()">上传</button>
    <progress id="progressBar" value="0" max="100"></progress>

    <script>
        const CHUNK_SIZE = 1024 * 1024;  // 每个分块的大小为 1MB

        function uploadFileInChunks() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            const progressBar = document.getElementById('progressBar');

            if (file) {
                let start = 0;
                let chunkIndex = 0;
                const totalChunks = Math.ceil(file.size / CHUNK_SIZE);

                function uploadChunk() {
                    const end = Math.min(start + CHUNK_SIZE, file.size);
                    const chunk = file.slice(start, end);

                    const formData = new FormData();
                    formData.append('chunk', chunk);
                    formData.append('chunkIndex', chunkIndex);
                    formData.append('totalChunks', totalChunks);
                    formData.append('fileName', file.name);

                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', 'http://127.0.0.1/index.php', true);

                    xhr.onload = function () {
                        if (xhr.status === 200) {
                            start = end;
                            chunkIndex++;
                            const percentComplete = (chunkIndex / totalChunks) * 100;
                            progressBar.value = percentComplete;

                            if (start < file.size) {
                                uploadChunk();
                            } else {
                                alert('文件上传完成');
                            }
                        }
                    };

                    xhr.send(formData);
                }

                uploadChunk();
            }
        }
    </script>
</body>
</html>

后端PHP代码如下:

<?php

// 设置允许跨域请求
header("Access-Control-Allow-Origin: *");

$chunk = $_FILES['chunk']['tmp_name'];
$chunkIndex = (int)$_POST['chunkIndex'];
$totalChunks = (int)$_POST['totalChunks'];
$fileName = $_POST['fileName'];

$uploadDir = './temp_uploads/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

$tempFilePath = $uploadDir . $fileName . '.part' . $chunkIndex;
move_uploaded_file($chunk, $tempFilePath);

if ($chunkIndex === $totalChunks - 1) {
    $outputFilePath = $uploadDir . $fileName;
    $outputFile = fopen($outputFilePath, 'wb');
    for ($i = 0; $i < $totalChunks; $i++) {
        $partFilePath = $uploadDir . $fileName . '.part' . $i;
        $partFile = fopen($partFilePath, 'rb');
        stream_copy_to_stream($partFile, $outputFile);
        fclose($partFile);
        unlink($partFilePath);
    }
    fclose($outputFile);
}

相关文章:

  • 搜广推校招面经十六
  • es和kibana安装
  • WEB安全--SQL注入--堆叠注入
  • 53倍性能提升!TiDB 全局索引如何优化分区表查询?
  • 关系数据库标准语言SQL
  • SQL语句语法
  • 【Java】xxl-job
  • print(f“Random number below 100: {random_number}“)的其他写法
  • 【Linux】:网络协议
  • c++--变量内存分配
  • C语言进阶习题【3】5 枚举——找单身狗2
  • Pytest快速入门
  • 【MySQL】第五弹---数据类型全解析:从基础到高级应用
  • Linux 上安装 PostgreSQL
  • AI时代:架构师的困境与救赎
  • 计时器任务实现(保存视频和图像)
  • 牛客小白月赛110
  • GGUF格式的DeepSeek-R1-Distill-Qwen-1.5B模型的字段解析
  • 机器学习·最近邻方法(k-NN)
  • 第七天:数据提取-正则表达式
  • 上海位居全球40城科技传播能力第六名
  • 当“诈骗诱饵”盯上短剧
  • 芬兰西南部两架直升机相撞坠毁,第一批救援队已抵达现场
  • 美国贸易政策|特朗普模式:你想做交易吗?
  • 广州医药集团有限公司原党委书记、董事长李楚源被“双开”
  • 蒲慕明院士:未来数十年不是AI取代人,而是会用AI的人取代不会用的