分片上傳文件處理

此需要基于webuploader.js插件
1. 前端代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webuploader</title>
</head>
<!--引入CSS-->
<link rel="stylesheet" type="text/css" href="/static/plugin/webuploader-0.1.5/webuploader.css">
<style>
    #upload-container, #upload-list{width: 500px; margin: 0 auto; }
    #upload-container{cursor: pointer; border-radius: 15px; background: #EEEFFF; height: 200px;}
    #upload-list{height: 800px; border: 1px solid #EEE; border-radius: 5px; margin-top: 10px; padding: 10px 20px;}
    #upload-container>span{widows: 100%; text-align: center; color: gray; display: block; padding-top: 15%;}
    .upload-item{margin-top: 5px; padding-bottom: 5px; border-bottom: 1px dashed gray;}
    .percentage{height: 5px; background: green;}
    .btn-delete, .btn-retry{cursor: pointer; color: gray;}
    .btn-delete:hover{color: orange;}
    .btn-retry:hover{color: green;}
</style>
<!--引入JS-->
<body>
<div id="upload-container">
    <span>點(diǎn)擊或?qū)⑽募献е链松蟼?lt;/span>
</div>
<div id="upload-list">
    <!-- <div class="upload-item">
        <span>文件名:123</span>
        <span data-file_id="" class="btn-delete">刪除</span>
        <span data-file_id="" class="btn-retry">重試</span>
        <div class="percentage"></div>
    </div> -->
</div>
<button id="picker" style="display: none;">點(diǎn)擊上傳文件</button>
</body>
<script type="text/javascript" src="https://jq.woshitime.top/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="/static/plugin/webuploader-0.1.5/webuploader.js"></script>
<script>
    $('#upload-container').click(function(event) {
        $("#picker").find('input').click();
    });
    var uploader = WebUploader.create({
        auto: true,// 選完文件后,是否自動(dòng)上傳。
        swf: '/static/plugin/webuploader-0.1.5/Uploader.swf',
        // 文件接收服務(wù)端。
        server: '{:Url("Index/fileupload")}',
        dnd: '#upload-container',
        pick: '#picker',// 內(nèi)部根據(jù)當(dāng)前運(yùn)行是創(chuàng)建,可能是input元素,也可能是flash. 這里是div的id
        // multiple: true, // 選擇多個(gè)
        chunked: true,// 開(kāi)起分片上傳。
        threads: 1, // 上傳并發(fā)數(shù)。允許同時(shí)最大上傳進(jìn)程數(shù)。
        // method: 'POST', // 文件上傳方式,POST或者GET。
        chunkSize:10*1024, //*1024*1024分片上傳,每片2M,默認(rèn)是5M
        fileVal:'upload', // [默認(rèn)值:'file'] 設(shè)置文件上傳域的name。
    });

    uploader.on('fileQueued', function(file) {
        // 選中文件時(shí)要做的事情,比如在頁(yè)面中顯示選中的文件并添加到文件列表,獲取文件的大小,文件類(lèi)型等
        // console.log(file.ext) // 獲取文件的后綴
        // console.log(file.size) // 獲取文件的大小
        // console.log(file.name);
        var html = '<div class="upload-item"><span>文件名:'+file.name+'</span><span data-file_id="'+file.id+'" class="btn-delete">刪除</span><span data-file_id="'+file.id+'" class="btn-retry">重試</span><div class="percentage '+file.id+'" style="width: 0%;"></div></div>';
        $('#upload-list').append(html);
    });

    uploader.on('uploadProgress', function(file, percentage) {
        console.log(percentage * 100 + '%');
        var width = $('.upload-item').width();
        $('.'+file.id).width(width*percentage);
    });

    uploader.on('uploadSuccess', function(file, response) {
        console.log(file.id+"傳輸成功");
    });

    uploader.on('uploadError', function(file) {
        console.log(file);
        console.log(file.id+'上傳出錯(cuò)')
    });

    $('#upload-list').on('click', '.upload-item .btn-delete', function() {
        // 從文件隊(duì)列中刪除某個(gè)文件id
        var file_id = $(this).data('file_id');
        // uploader.removeFile(file_id); // 標(biāo)記文件狀態(tài)為已取消
        uploader.removeFile(file_id, true); // 從queue中刪除
        console.log(uploader.getFiles());
    });

    $('#upload-list').on('click', '.btn-retry', function() {
        uploader.retry($(this).data('file_id'));
    });

    uploader.on('uploadComplete', function(file) {
        console.log(uploader.getFiles());
    });
</script>
</html>
2. 后端代碼

class upload
{
    private $filepath = './webuploader'.DIRECTORY_SEPARATOR.'file_material'; //上傳目錄
    private $fileTmpPath = './webuploader'.DIRECTORY_SEPARATOR.'file_material_tmp'; //上傳目錄
    private $tmpPath; //PHP文件臨時(shí)目錄
    private $blobNum; //第幾個(gè)文件塊
    private $totalBlobNum; //文件塊總數(shù)
    private $fileName; //文件名

    public function __construct($tmpPath,$blobNum,$totalBlobNum,$fileName){
        $this->tmpPath = $tmpPath;
        $this->blobNum = $blobNum;
        $this->totalBlobNum = $totalBlobNum-1;
        $this->fileName = $fileName;

        $this->moveFile();
        $this->fileMerge();
    }

    //判斷是否是最后一塊,如果是則進(jìn)行文件合成并且刪除文件塊
    private function fileMerge(){
        if($this->blobNum == $this->totalBlobNum){
            $blob = '';
            for($i=0; $i<= $this->totalBlobNum; $i++){
                $blob .= file_get_contents($this->fileTmpPath.'/'. $this->fileName.'__'.$i);
            }
            file_put_contents($this->filepath.'/'. $this->fileName,$blob);
            $this->deleteFileBlob();
        }
    }

    //刪除文件塊
    private function deleteFileBlob(){
        for($i=0; $i<= $this->totalBlobNum; $i++){
            @unlink($this->fileTmpPath.'/'. $this->fileName.'__'.$i);
        }
    }

    //移動(dòng)文件
    private function moveFile(){
        $this->touchDir();
        $filename = $this->fileTmpPath.'/'. $this->fileName.'__'.$this->blobNum;
        move_uploaded_file($this->tmpPath,$filename);
    }

    //API返回?cái)?shù)據(jù)
    public function apiReturn(){
        $data = [];
        if($this->blobNum == $this->totalBlobNum){
            if(file_exists($this->filepath.'/'. $this->fileName)){
                $data['code'] = 2;
                $data['msg'] = 'success';
                $data['file_path'] = 'http://'.$_SERVER['HTTP_HOST'].str_replace('.','',$this->filepath).'/'. $this->fileName;
            }
        }else{
            if(file_exists($this->fileTmpPath.'/'. $this->fileName.'__'.$this->blobNum)){
                $data['code'] = 1;
                $data['msg'] = 'waiting for all';
                $data['file_path'] = '';
            }
        }
        return json_encode($data);
    }

    //建立上傳文件夾
    private function touchDir(){
        if(!file_exists($this->filepath)){
            if (!mkdir($concurrentDirectory = $this->filepath) && !is_dir($concurrentDirectory)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
            }
        }
        if(!file_exists($this->fileTmpPath)){
            if (!mkdir($concurrentDirectory = $this->fileTmpPath) && !is_dir($concurrentDirectory)) {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $concurrentDirectory));
            }
        }
    }
}
3. 控制器代碼
public function fileupload()
{
    $file = $_FILES['upload'];

    $id = input("id");
    $fileName = cache($id);
    if (!$fileName){
        $fileName = md5(time().uniqid(random_int(0,99999),true)).'.'.pathinfo($file['name'])['extension'];
    }
    cache($id,$fileName,10);
    $chunk = input("chunk",0);
    $chunks = input("chunks",1);

    $upload = new upload($file['tmp_name'],$chunk,$chunks,$fileName);
    echo $upload->apiReturn();
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容