webupload 實現大文件分片上傳

廢話不多說,直接上例子:

 

html代碼:

<div class="layui-form-item" >
       <label for="" class="layui-form-label">選擇文件</label>
       <div class="layui-input-block" id="file">
                 
       </div>
</div>

引入css樣式文件:

<link rel ="slylesheet" type="text/css" href="/backwebuploader/webuploader0.1.5/webuploader.css">

引入js文件:

<script src="/backwebuploader/webuploader0.1.5/webuploader.js" charset="utf-8"></script>

jQuery代碼:

        var $list = $("#file");
        // webupload 上傳
        var uploader = WebUploader.create({
            // pick: "#file", // 選擇文件的按鈕。可選
            pick: { id: '#file', multiple: false, innerHTML: '選擇文件' },
            swf: '__PUBLIC__/backwebuploader/webuploader0.1.5/uploader.swf', // swf文件路徑
            server: "url", // 文件接收服務端url。
            auto: true,
            threads: 1,//併發數
            chunked: true, //是否要分片處理大文件上傳
            chunkSize: 2 * 1024 * 1024, //分片上傳,每片2M
            fileSizeLimit: 2 * 1024 * 1024 * 1024,    // 所有文件總大小限制
            fileSingleSizeLimit: 2 * 1024 * 1024 * 1024,    // 單個文件大小限制
            formData: {
                // 自定義參數
                // guid: WebUploader.Base.guid()
            },
            accept: {
                title: 'Video',
                extensions: 'mp4,avi,rm,iso,wmv,mkv', // 文件類型
                mimeTypes: 'video/*'
            },
            duplicate: true,
        });

        // 當有文件被添加進隊列的時候
        uploader.on( 'fileQueued', function( file ) {
            
            $list.append( '<div id="' + file.id + '" class="item">' +
                '<h4 class="info">' + file.name + '</h4>' +
                '<p class="state">等待上傳...</p>' +
            '</div>' );

        });

        uploader.on('error', function (error) {
            if (error == 'Q_EXCEED_SIZE_LIMIT') {
                layer.msg('請選擇小於2G的文件')
            }
        });


        // 文件上傳過程中創建進度條實時顯示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress .progress-bar');

            // 避免重複創建
            if ( !$percent.length ) {
                $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
            }

            $li.find('p.state').text('正在上傳。。。。');
            $percent.css( 'width', percentage * 100 + '%' );
            $percent.html( percentage * 100 + '%' );
        });

        // 文件上傳成功
        uploader.on( 'uploadSuccess', function( file,response) {
            $( '#'+file.id ).find('p.state').text('已上傳');
            $list.append('<video src="'+ response.filePath +'" id="video_url" controls="controls" style="width: 150px; height: 150px;"></video>');
            
        });

        // 文件上傳失敗,顯示上傳出錯
        uploader.on( 'uploadError', function(file, response) {
            $( '#'+file.id ).find('p.state').text('上傳出錯');
        });
        // 完成上傳完
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').fadeOut();
        });

服務端(php):

    public function uploads()
    {
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Content-type: text/html; charset=gbk32");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        // header("HTTP/1.0 500 Internal Server Error");
        // exit;
        // 5 minutes execution time
        set_time_limit(5 * 60);
        // Uncomment this one to fake upload time
         usleep(5000);
        // Settings
        $targetDir = 'tmp'.DIRECTORY_SEPARATOR.$myTmp;            //存放分片臨時目錄
       
        $uploadDir = DIRECTORY_SEPARATOR..date('Ymd');    //分片合併存放目錄
        
 
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
 
        // Create target dir

        if (!file_exists($targetDir)) {
            mkdir($targetDir,0777,true);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir,0777,true);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");

        }
       
        $oldName = $fileName;
       
        $fileName = iconv('UTF-8','gb2312',$fileName);
       
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                // die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory111."}, "id" : "id"}');
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory111."}, "id" : "id"}');
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }
        // Open temp file
        if (!$out = fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.1", "error" : {"code": 102, "message": "Failed to open output stream222."}, "id" : "id"}');
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.2", "error" : {"code": 103, "message": "Failed to move uploaded file333."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if (!$in = fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.3", "error" : {"code": 101, "message": "Failed to open input stream444."}, "id" : "id"}');
            }
        } else {
            if (!$in = fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.4", "error" : {"code": 101, "message": "Failed to open input stream555."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        fclose($out);
        fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
 
        if ($done) {
            $pathInfo = pathinfo($fileName);
            
            $hashStr = substr(md5($pathInfo['basename']),8,16);
            $hashName = time() . $hashStr . '.' .$pathInfo['extension'];
            $uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName;
            if (!$out = fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.5", "error" : {"code": 102, "message": "Failed to open output stream666."}, "id" : "id"}');
            }
            //flock($hander,LOCK_EX)文件鎖
            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    fclose($in);
                    unlink("{$filePath}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            fclose($out);

            $response = [
                'success'=>true,
                'oldName'=>$oldName,
                'filePath'=> $uploadPath,
                'fileSuffixes'=>$pathInfo['extension'],          //文件後綴名
                'fileInfo' => $pathInfo,
            ];

            return json($response);
        }
 
        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.6", "result" : null, "id" : "id"}');
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章