1. 程式人生 > >tp5大檔案上傳

tp5大檔案上傳

====== 配置php.ini ====
max_execution_time = 6000
max_input_time = 6000
post_max_size = 90000M
upload_max_filesize = 80000M
max_file_uploads = 200

======= html ===

<div id="uploader" class="wu-example">
	<!--用來存放檔案資訊-->
	<div id="thelist" class="uploader-list"></div>
	<div class="btns">
		<div id="picker">選擇檔案</div>
	</div>
</div>

====== js ========

function uploadModel() {
    // 建立上傳
    var uploader = WebUploader.create({
        auto: true, // 選中檔案後,自動上傳
        swf: '/static/public/webupload/Uploader.swf',
        server: './upload',      // 服務端地址
        pick:'#picker',
        resize: false,
        chunked: true,            //開啟分片上傳
        chunkSize: 1024*1024*100,   //每一片的大小
        chunkRetry: 5,          // 如果遇到網路錯誤,重新上傳次數
        threads: 1,               // [預設值:3] 上傳併發數。允許同時最大上傳程序數。
        fileNumLimit:500,
        fileSizeLimit:1024*1024*1024*10,
        fileSingleSizeLimit:1024*1024*1024*10,
        formData: {model_type:model_type}
    });
    // 當有檔案被新增進佇列的時候
    uploader.on( 'fileQueued', function( file ) {
        var $list = $('#thelist');
        $list.html('');
        $list.append( '<div id="' + file.id + '" class="item">' +
            '<h4 class="info">' + file.name + '</h4>' +
            '<p class="state">等待上傳...</p>' +
            '</div>' );
    });
    // 檔案上傳過程中建立進度條實時顯示。
    uploader.on( 'uploadProgress', function( file, percentage ) {
        var $li = $( '#'+file.id ),
            $percent = $li.find('.layui-progress .layui-progress-bar');
        // 避免重複建立
        if ( !$percent.length ) {
            $percent = $('<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="demo">' +
                '<div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>'+
                '</div>').appendTo( $li ).find('.layui-progress-bar');
        }
        $li.find('p.state').text('上傳中');
        element.progress('demo', percentage * 100 + '%');
        /*$percent.css( 'width', percentage * 100 + '%' );
        $percent.css( 'lay-percent', percentage * 100 + '%' );*/
    });

    //模型上傳成功
    uploader.on('uploadSuccess', function (file, response) {
        $( '#'+file.id ).find('p.state').text('合併和解壓中...');
        $.ajax({
            url: "./saveFile",
            type: "post",
            data: {
                oldName:response.oldName,
                uploadPath:response.filePaht,
                extension:response.fileSuffixes,
                path:response.path
            },
            dataType: "json",
            success: function (res) {
                if(res.code==2){
                    $( '#'+file.id ).find('p.state').text('上傳成功');
                    $('#resource_name').val(file.name);
                    attachment_id = res.id;
                    layer.msg(res.msg);
                }else{
                    $( '#'+file.id ).find('p.state').text('合併解壓出錯,請重新上傳');
                }
            }
        });
    });

    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上傳出錯');
    });
}


============ tp5  php =======

// 上傳分片檔案,合併分片檔案
public function upload(){
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        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; }
        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        @set_time_limit(30 * 60);
        $path = 'E:\WebServer\Resources'; //檔案路徑
        $date_dir = date('Ymd');
        $targetDir = $path . '\\' . 'file_material_tmp' . '\\' . $date_dir;
        $uploadDir = $path . '\\' . 'file_material' . '\\' . $date_dir;
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 10 * 3600; // Temp file age in seconds
        if (!is_dir($targetDir)) {
            mkdir($targetDir, 0777, true);
        }
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } else if (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $oldName = $fileName;
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        $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 directory."}, "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.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $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.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }
            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,
                'filePaht'=>$uploadPath,
                'fileSuffixes'=>$pathInfo['extension'],
                'path'=>$path
            ];
            return json($response);
        }
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }
	
	// 儲存上傳的壓縮包並解壓
	 public function saveFile()
    {
        $param = input('post.');
        $oldName = $param['oldName'];
        $uploadPath = $param['uploadPath'];
        $extension = $param['extension'];
        $path = $param['path'];
        //寫入到檔案表
        $data = [];
        $data[''] = $oldName;
		...(自己根據需求存檔案)
        
        $res['src'] = $uploadPath;
        $res['code'] = 2;
        // 記得開啟php.ini裡的com.allow_dcom = true
		// 電腦裡安裝的有winrar
        $obj = new \COM('WScript.Shell');
        //執行doc解壓命令
        $file_path = $res['src'];
        $flag = $obj->run("winrar x $file_path $path",1,true);
        if($flag == 1){ // 0 是成功 1是失敗
            return json(['code'=>-1,'msg'=>'解壓檔案失敗']);
        }
        $res['id'] = Db::name('attachment')->insertGetId($data);
        return json($res);
    }

G M T
檢測語言世界語中文簡體中文繁體丹麥語烏克蘭語烏茲別克語烏爾都語亞美尼亞語伊博語俄語保加利亞語信德語修納語僧伽羅語克羅埃西亞語冰島語加利西亞語加泰羅尼亞語匈牙利語南非祖魯語卡納達語盧森堡語印地語印尼巽他語印尼爪哇語印尼語古吉拉特語吉爾吉斯語哈薩克語土耳其語塔吉克語塞爾維亞語塞索托語夏威夷語威爾士語孟加拉語宿務語尼泊爾語巴斯克語布林語(南非荷蘭語)希伯來語希臘語庫爾德語弗裡西語德語義大利語意第緒語拉丁語拉脫維亞語挪威語捷克語斯洛伐克語斯洛維尼亞語斯瓦希里語旁遮普語日語普什圖語喬治亞語毛利語法語波蘭語波斯尼亞語波斯語泰盧固語泰米爾語泰語海地克里奧爾語愛爾蘭語愛沙尼亞語瑞典語白俄羅斯語科薩科西嘉語立陶宛語索馬利亞語約魯巴語緬甸語羅馬尼亞語寮國語芬蘭語蘇格蘭蓋爾語苗語英語荷蘭語菲律賓語薩摩亞語葡萄牙語蒙古語西班牙語豪薩語越南語亞塞拜然語阿姆哈拉語阿爾巴尼亞語阿拉伯語韓語馬其頓語馬爾加什語馬拉地語馬拉雅拉姆語馬來語馬耳他語高棉語齊切瓦語 世界語中文簡體中文繁體丹麥語烏克蘭語烏茲別克語烏爾都語亞美尼亞語伊博語俄語保加利亞語信德語修納語僧伽羅語克羅埃西亞語冰島語加利西亞語加泰羅尼亞語匈牙利語南非祖魯語卡納達語盧森堡語印地語印尼巽他語印尼爪哇語印尼語古吉拉特語吉爾吉斯語哈薩克語土耳其語塔吉克語塞爾維亞語塞索托語夏威夷語威爾士語孟加拉語宿務語尼泊爾語巴斯克語布林語(南非荷蘭語)希伯來語希臘語庫爾德語弗裡西語德語義大利語意第緒語拉丁語拉脫維亞語挪威語捷克語斯洛伐克語斯洛維尼亞語斯瓦希里語旁遮普語日語普什圖語喬治亞語毛利語法語波蘭語波斯尼亞語波斯語泰盧固語泰米爾語泰語海地克里奧爾語愛爾蘭語愛沙尼亞語瑞典語白俄羅斯語科薩科西嘉語立陶宛語索馬利亞語約魯巴語緬甸語羅馬尼亞語寮國語芬蘭語蘇格蘭蓋爾語苗語英語荷蘭語菲律賓語薩摩亞語葡萄牙語蒙古語西班牙語豪薩語越南語亞塞拜然語阿姆哈拉語阿爾巴尼亞語阿拉伯語韓語馬其頓語馬爾加什語馬拉地語馬拉雅拉姆語馬來語馬耳他語高棉語齊切瓦語
文字轉語音功能僅限200個字元
選項 : 歷史 : 反饋 : Donate 關閉