PHP 之分片上传

一、效果图

二、前端

复制代码
<template>
    <div>
        <el-upload ref="uploadRef" 
        :show-file-list="false" 
        class="upload" 
        :auto-upload="false" 
        :on-change="handleChange"
        :limit="1" 
        :http-request="test"
        :on-exceed="test"
        >
            <el-button type="primary">文件上传</el-button>
        </el-upload>

        <el-progress :percentage="percent" :stroke-width="10" :status="status" />
    </div>
</template>

<script setup>
    import {
        getCurrentInstance,
        ref
    } from 'vue';
    
    const {proxy} = getCurrentInstance()
    const uploadRef = ref()
    
    const percent = ref(0)
    const status = ref('')

    const handleChange = (uploadFile, uploadFiles) => {
        console.log(uploadFile, uploadFiles, uploadFile.raw instanceof File)
        status.value = ''
        percent.value = 0
        
        const file = uploadFile.raw;
        const CHUNK_SIZE = 1024 * 1024 * 5; // 分片大小,例如5MB
        const CHUNKS = Math.ceil(file.size / CHUNK_SIZE); // 总分片数
        let uploaded = 0; // 已上传的分片数
        console.log(CHUNKS);

        const uploadChunk = async (chunkIndex) => {
            const start = chunkIndex * CHUNK_SIZE;
            const end = (chunkIndex + 1) * CHUNK_SIZE;
            const chunk = file.slice(start, end);
            const formData = new FormData();
            formData.append('file', chunk); // 注意:服务器端需要处理这种分片上传的情况
            formData.append('chunkIndex', chunkIndex); // 添加分片索引信息
            formData.append('totalChunks', CHUNKS); // 添加总分片数信息
            formData.append('fileName', file.name); // 可选,添加文件名信息
            
            console.log(chunk, formData)
            let res = await proxy.$http.post('upload.php', formData)
            console.log(res)
            if(res.code == 0) {
                uploaded++;
                updateProgress();
                //更新进度条
                if(chunkIndex + 1 == CHUNKS) {
                    console.log('上传成功 ==> ', res.fileInfo)
                    // alert(res.msg)
                    status.value = 'success';
                    uploadRef.value.clearFiles()
                }else{
                    uploadChunk(uploaded)
                }
            }else{
                console.log(res.msg);
            }
        }
        
        const updateProgress = () => {
            const percentVal = parseInt(parseFloat(uploaded / CHUNKS).toFixed(2) * 100)
            percent.value = percentVal
        }
        
        uploadChunk(0);
    }
    
    const test = (file) => {
        console.log(file)
    }
</script>

<style>
</style>

三、后端

复制代码
<?php

// var_dump($_FILES);
$chunkIndex = intval($_POST['chunkIndex']);
$fileName = trim($_POST['fileName']);
$totalChunks = intval($_POST['totalChunks']);

$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$temp_name = md5($fileName).'_{0}.txt';
$uploadFile = str_replace('{0}', $chunkIndex, $temp_name);
if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
    //合并文件
    $f = md5($fileName).'.'.$ext;
    if($chunkIndex + 1 == $totalChunks){
        $filesize = 0;
        for($i = 0; $i < $totalChunks; $i++){
            $file = str_replace('{0}', $i, $temp_name);
            if(file_exists($file)){
                //合并文件
                $content = file_get_contents($file);
                $filesize += strlen($content);
                file_put_contents($f, $content, FILE_APPEND);
                unlink($file);
            }
        }
        $fileInfo = array(
            'filename' => $fileName,
            'filesize' => $filesize,
            'path' => $f,
            'fileext' => $ext,
        );
        die(json_encode(array('code' => 0, 'msg' => '上传成功', 'fileInfo' => $fileInfo)));
    }
    die(json_encode(array('code' => 0, 'msg' => '上传成功')));
}else{
    die(json_encode(array('code' => 1, 'msg' => '上传失败')));
}
相关推荐
神仙别闹12 小时前
基于 C# OpenPGP 的文件管理系统
开发语言·c#
番石榴AI12 小时前
纯 CPU 推理!0.1B 超轻量级端到端OCR模型,使用 Java 进行文档解析
java·开发语言·ocr
likerhood12 小时前
ConcurrentHashMap详细讲解(java)
java·开发语言·性能优化
机器学习之心12 小时前
集成BWM法、熵权法、改进博弈论组合赋权与三角直觉模糊云模型的多属性评价模型,MATLAB代码
开发语言·matlab·熵权法·三角直觉模糊云模型·bwm法·改进博弈论组合赋权·多属性评价模型
特种加菲猫13 小时前
二叉搜索树:数据世界的“快速寻路指南”
开发语言·c++
特种加菲猫13 小时前
STL关联容器:Set/Multiset与Map/Multimap详解
开发语言·c++
我滴老baby13 小时前
0基础速通Python+AI|2026热门轻量化玩法全攻略:从入门到实战,3天搞定AI应用开发
开发语言·人工智能·python
一个天蝎座 白勺 程序猿13 小时前
Python(29)Python生成器函数深度解析:asyncio事件循环的底层实现与异步编程实战
开发语言·python
2zcode13 小时前
原创文档:基于MATLAB的线性预测编码变声器系统
开发语言·matlab·语音识别
七夜zippoe13 小时前
Python RESTful API设计终极指南:从理论到企业级实战
开发语言·python·http·pandas·restful api