Webupload+PHP上传大文件
生活随笔
收集整理的這篇文章主要介紹了
Webupload+PHP上传大文件
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
今天來寫寫上傳文件這件‘小事’
本文把我以前編寫上傳文件記錄一下,給以后的自己備用和吐槽
需要用到的東西
- WebUpload 官網(wǎng)下載
- PHP
開始
引入webupload.js
<script type="text/javascript" src="./webupload/webuploader.js"></script>然后修改樣式,我的樣式如下:
* {-webkit-box-sizing: border-box;-moz-box-sizing: border-box;box-sizing: border-box; } .fl{float: left; } .fr{float: right; } label {display: inline-block;max-width: 100%;margin-bottom: 5px;font-weight: 700; } /*按鈕*/ #picker {width: 100px;height: 100px;background: #eee;border: 1px solid #cacaca; } #picker .webuploader-pick {background: #eee!important;width: 100%!important;height: 100%!important;line-height: 98px;font-size: 18px;color: #999;padding: 0; } .webuploader-element-invisible {position: absolute !important;clip: rect(1px 1px 1px 1px);clip: rect(1px,1px,1px,1px); } .webuploader-container {position: relative;display: inline-block;vertical-align: top; } .webuploader-pick {position: relative;display: inline-block;cursor: pointer;background: #3bb4f2;padding: 4px 12px;color: #fff;text-align: center;border-radius: 3px;overflow: hidden; } /*上傳列表*/ .item{width: 300px;height: 70px;background: #F1F1F1;border: 1px solid #c3c3c3;padding: 5px 10px;position: relative;font-size: 14px;color: #545454;margin-bottom: 15px;box-sizing: content-box; } .item h4{margin: 0 0 6px;font-size: 16px;width: 180px;height: 22px;line-height: 22px;white-space:nowrap;-ms-text-overflow: ellipsis;text-overflow: ellipsis;overflow: hidden; } .item .progress{height: 5px;width: 100%;margin: 0;background: #aaa; } .item .progress-bar{height: 100%;background: #676565;width: 0; } .item .start_upload{} .item .progress-txt{margin-top:10px;width: 200px;height: 26px;line-height: 26px;overflow: hidden;white-space:nowrap;-ms-text-overflow: ellipsis;text-overflow: ellipsis;overflow: hidden; } .item .del_upload{position: absolute;right: 10px;top: 5px;cursor: pointer; } .item .del_upload:hover{color: #333;font-weight: 600; } .item .stop_upload,.start_upload,.again_upload,.continue_upload{width: 83px;margin-top: 10px;height: 26px;line-height: 26px;text-align: center;background: #d8d8d8;border-radius: 3px;display: none;cursor: pointer; } .item .stop_upload:hover,.start_upload:hover,.again_upload:hover,.continue_upload:hover{background: #cacaca; } .item .current{display: block; }html
<!DOCTYPE HTML> <html> <head><meta charset="utf-8"><meta name="renderer" content="webkit|ie-comp|ie-stand"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" /><meta http-equiv="Cache-Control" content="no-siteapp" /><link href="default.css" rel="stylesheet" type="text/css" /><title>上傳文件</title> </head> <body> <div id="imgUploadCtn"><div class="btns"><div id="picker">選擇文件</div><div id="thelist" class="uploader-list"></div><div id="imgCtn"></div></div> </div> <script src="jquery-2.1.1.min.js"></script> <script src="./webupload/webuploader.js"></script> <script src="default.js"></script> </body> </html>js
$(function () {var uploader = WebUploader.create({// swf文件路徑swf: './webupload/Uploader.swf',// 文件接收服務(wù)端。server: './fileUpload_set',//后綴名驗(yàn)證accept:{title:'zip',extensions:'zip',mimeTypes:'.zip'},//分片上傳chunked:true,//分片上傳大小 這是2MchunkSize:1024*1024*2,//文件并發(fā)數(shù) 因?yàn)槭欠制信判蛞?guī)則所以并發(fā)數(shù)為1threads:1,// 選擇文件的按鈕。可選。// 內(nèi)部根據(jù)當(dāng)前運(yùn)行是創(chuàng)建,可能是input元素,也可能是flash.pick: '#picker',//限制文件總數(shù)fileNumLimit:1,// 不壓縮image, 默認(rèn)如果是jpeg,文件上傳前會(huì)壓縮一把再上傳!resize: false})// 當(dāng)有文件被添加進(jìn)隊(duì)列的時(shí)候var $list=$('#thelist');//隨機(jī)碼var randCode='';uploader.on( 'fileQueued', function( file ) {$list.append( '<div id="' + file.id + '" class="item">' +'<h4 class="info">' + file.name + '</h4>' +'<div class="progress progress-striped active">' +'<div class="progress-bar" role="progressbar"></div></div>'+'<div class="state progress-txt fl" title="">等待上傳...</div>' +'<div id="' + file.id + '_del" class="del_upload fr" data-id="' + file.id + '">刪除</div>' +'<div id="' + file.id + '_stop" class="stop_upload fr" data-id="' + file.id + '">停止</div>' +'<div id="' + file.id + '_continue" class="continue_upload fr" data-id="' + file.id + '">繼續(xù)</div>' +'<div id="' + file.id + '_upload" class="start_upload fr current" data-id="' + file.id + '">開始上傳</div>' +'<div id="' + file.id + '_again" class="again_upload fr " data-id="' + file.id + '">重新上傳</div>' +'</div>');//刪除$list.on('click','#'+file.id+'_del',function () {uploader.cancelFile(file);$(this).closest('.item').remove();});//停止$list.on('click','#'+file.id+'_stop',function () {$(this).removeClass('current');$(this).parent('.item').find('.again_upload').addClass('current');/*uploader.stop(file);*/uploader.cancelFile(file);console.log(uploader.getStats());})//繼續(xù)上傳$list.on('click','#'+file.id+'_continue',function () {$(this).removeClass('current');$(this).parent('.item').find('.stop_upload').addClass('current');uploader.upload(file);})//開始上傳$list.on('click','#'+file.id+'_upload',function () {$(this).removeClass('current');$(this).parent('.item').find('.stop_upload').addClass('current');randCode=rand(15);uploader.upload(file);})//重傳$list.on('click','#'+file.id+'_again',function () {$(this).removeClass('current');$(this).parent('.item').find('.stop_upload').addClass('current');randCode=rand(15);uploader.upload(file.id);});});// 文件上傳過程中創(chuàng)建進(jìn)度條實(shí)時(shí)顯示。uploader.on( 'uploadProgress', function( file, percentage ) {var $li = $( '#'+file.id ),$percent = $li.find('.progress .progress-bar');// 避免重復(fù)創(chuàng)建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('.state').text('上傳中 - '+parseInt(percentage * 100) + '%');$percent.css( 'width', parseInt(percentage * 100) + '%' );});//文件成功處理uploader.on( 'uploadSuccess', function( file ,data) {//data 為服務(wù)器返回的數(shù)據(jù)//console.log(data);if(data.status=='ok'){if ($('#successInfo').length){$('#successInfo').remove();}$('<div id="successInfo"><img src="'+data.info.img+'" alt=""><input type="hidden" name="picupload" value="'+data.info.img+'">' +'<input type="hidden" name="fileupload" value="'+data.info.zip+'"></div>').appendTo('#imgCtn');$( '#'+file.id ).find('.state').text('上傳完成 - 100%');subTime();}else{$( '#'+file.id ).find('.state').text(data.info);};});//文件失敗處理uploader.on( 'uploadError', function( file ) {$( '#'+file.id ).find('p.state').text('上傳出錯(cuò)');});//上傳失敗獲成功都會(huì)執(zhí)行uploader.on('uploadComplete',function (file) {$('#'+file.id).find('.current').removeClass('current');$('#'+file.id).find('.again_upload').addClass('current');})//文件加入隊(duì)列前執(zhí)行uploader.on('beforeFileQueued', function (file) {});//主要用來詢問是否要添加附帶參數(shù),大文件在開起分片上傳的前提下此事件可能會(huì)觸發(fā)多次uploader.on('uploadBeforeSend',function (file,data) {//隨機(jī)碼data.randCode=randCode;});//當(dāng)所有文件上傳完成uploader.on('uploadFinished',function (file,data) {});//開始上傳$('#ctlBtn').on('click', function() {uploader.upload();});// 初始化以后添加 參數(shù)//uploader.options.formData.uid = 456789;//隨機(jī)碼function rand(i) {var str='123456789qwertyiopasdfghjklzxcvbnm';var strLen=str.length;var newStr='';Math.random()*strLen;while(i>0){newStr+=str[parseInt(Math.random()*strLen)];i--;}return newStr;}var t;function subTime() {var i=100;if (t){clearInterval(t);}t=setInterval(function () {$('#submit span').text('('+i+'秒后)自動(dòng)提交');if (i==0){clearInterval(t);$('#submit span').text('提交作品');$('#submit').click();return;};i--;},1000);}})PHP代碼
<? //文件上傳 public function fileUpload_set(){$path="./file/cookie/zip";$imgPath="./file/cookie/img/";$maxSize=20*1024*1024;$exts=['zip'];$file=new FileUploadClass();/*** 上傳文件* @param $mPath 保存地址* @param string $mMaxSize 限制文件大小 單位b* @param array $mExts 限制文件格式 array* @return bool*/$msg=$file->fileSave($path,$imgPath,$maxSize,$exts);return $this->msg($msg['status'],$msg['info']); } ?>PHP合并文件類
<?php /*** Created by PhpStorm.* User: Administrator* Date: 2017-07-13* Time: 上午 11:14*/class FileUploadClass {public $msg=[];/*** 上傳文件* @param $mPath 保存地址* @param string $mMaxSize 限制文件大小 單位b* @param array $mExts 限制文件格式 array* @return bool*/public function fileSave($mPath,$mMaxSize=20*1024*1024,$mExts=[]){if (strpos($mPath,'.')!==0){$mPath='.'.$mPath;}$arr=explode('/',$mPath);$aimUrl='';foreach($arr as $str){$aimUrl.=$str.'/';if(!file_exists($aimUrl)){mkdir($aimUrl,0777);chmod($aimUrl,0777);}}if (!file_exists($aimUrl)) {$this->msg('error','創(chuàng)建目錄失敗');return false;}else{$upload = new \org\Upload();$upload->maxSize = $mMaxSize;if($mExts){$upload->exts = $mExts;}$upload->rootPath = $aimUrl;$upload->driver = "Local";$upload->saveName = ['uniqid', ''];$info = $upload->upload();if (!$info) {$this->msg('error',$upload->getError());return false;} else {$aimUrl=str_replace('./','/',$aimUrl);//這里$infoyn[0]是指你上傳第一個(gè)圖片的信息,你如果上傳N個(gè)圖片就會(huì)有$infoyn[N]if(isset($info[0]['savepath'])){$filePath=$aimUrl . $info[0]['savepath'] . $info[0]['savename'];}else{$filePath=$aimUrl . $info['file']['savepath'] . $info['file']['savename'];//獲取文件格式$ext=substr($info['file']['savename'],strrpos($info['file']['savename'],'.'));//文件合并(分片上傳)if(!empty($_POST['chunks'])&&$_POST['chunks']!=1){return $this->fileCombine($_POST['randCode'].$ext,$mPath,'.'.$filePath,$info['file']['savename']);}}$this->msg('ok',$filePath,['fileName'=>$info['file']['name']]);return true;}}return true;}/*** 文件合并* @param $filename 上傳的文件名* @param $mPath 緩存文件夾路徑* @param $filesAddr 文件詳細(xì)地址* @param $savename 保存文件的新名稱* @return array*/public function fileCombine($filename,$mPath,$filesAddr,$savename){$oldPath=$mPath.'/'.$filename;$newPath=$mPath.'/'.$savename;if (!file_exists($mPath)){@mkdir($mPath,0777);}if(file_put_contents($oldPath,file_get_contents($filesAddr),FILE_APPEND)){if ($_POST['chunks']==$_POST['chunk']+1){@rename($oldPath,$newPath);}$this->msg('ok',$newPath);@unlink($filesAddr);return true;}else{$this->msg('error','文件合并失敗');@unlink($filesAddr);return false;};}/*** 移動(dòng)文件* @param $filePath 文件原路徑支持?jǐn)?shù)組{a,b~~},字符串 "a,b,c~~"或 "a"* @param $movePath 移動(dòng)后的目錄地址* @return array*/function fileMove($filePath,$movePath){if(is_string($filePath)){$imgArr=explode(',',$filePath);}elseif(is_array($filePath)){$imgArr=$filePath;}else{$this->msg('error','文件路徑只能為字符串或數(shù)組');return false;}foreach ($imgArr as $vo){if (!empty($vo)){if(strpos($vo,'.')!==0){$vo=".".$vo;}if(strpos($movePath,'.')!==0){$movePath=".".$movePath;}if(!file_exists($vo)){$this->msg('error','目標(biāo)文件不存在');return false;}else{$fileName=substr($vo,strrpos($vo,'/')+1);$fileArr=explode('/',$movePath);$aimUrl='';foreach($fileArr as $v){$aimUrl.=$v.'/';if (!file_exists($aimUrl)){if(mkdir($aimUrl,0777,true)){$this->msg('error','創(chuàng)建文件夾失敗');return false;};//取得文件最大權(quán)限chmod($aimUrl, 0777);}}//移動(dòng)文件if(!rename($vo , $movePath.$fileName)){$this->msg('error','移動(dòng)文件失敗');return false;};}}}$this->msg('ok',$movePath.$fileName);return true;}/*** 刪除文件* @param $dir 刪除的文件路徑 或 目錄* @return bool*/function fileDelete($dir){if (strpos($dir,'.')!==0){$dir='.'.$dir;}if (filetype($dir)=='dir'){if ($dh=opendir($dir)){while (($file=readdir($dh))!==false){if($file=='.'||$file=='..'){continue;}if (filetype($dir.'/'. $file)=='dir'){if (!$this->deleteFiles($dir.'/' . $file)){return false;}if(!rmdir($dir.'/'.$file)){$this->msg('error','刪除失敗('.$dir.'/'.$file.')');return false;}}else{if(!unlink($dir.'/' . $file)){$this->msg('error','刪除失敗('.$dir.'/'.$file.')');return false;}}}closedir($dh);}}else{if(!@unlink($dir)){$this->msg('error','刪除失敗');return false;}}return true;}/*** 下載文件* @param $filePath 目標(biāo)文件的路勁* @param string $filename 下載時(shí)顯示的名稱* @return bool*/public function fileDownload($filePath,$filename=''){if(empty($filePath)){$this->msg('error','缺少文件路勁');return false;}if (strpos($filePath,'.')!==0){$filePath='.'.$filePath;}if (is_file($filePath)) {$length = filesize($filePath);if ($filename){$ext=strrchr($filePath,'.');$showname = $filename.$ext;}else{$showname = ltrim(strrchr($filePath, '/'), '/');}$realpath =realpath($filePath);header("Content-Description: File Transfer");header('Content-type: application/octet-stream');header('Content-Length:' . $length);if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IEheader('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');} else {header('Content-Disposition: attachment; filename="' . $showname . '"');}header("X-Sendfile: $realpath");exit;} else {$this->msg('error','文件不存在!');return false;}}public function msg($status,$info,$other=[]){$arr=['status'=>$status,'info'=>$info];if ($other){$arr['other']=$other;}return $this->msg = $arr;} }注意:
$upload = new \org\Upload();這是就是一個(gè)上傳文件的約束類你完全可以用$_FILES來獲取上傳文件信息
我把文件整個(gè)分享出來:網(wǎng)盤下載
下載整個(gè)文件后 \org\Upload() 參數(shù)的使用:
/*** 默認(rèn)上傳配置* @var array*/private $config = [// 允許上傳的文件MiMe類型'mimes' => [],// 上傳的文件大小限制 (0-不做限制)'maxSize' => 0,// 允許上傳的文件后綴'exts' => [],// 自動(dòng)子目錄保存文件'autoSub' => true,// 子目錄創(chuàng)建方式,[0]-函數(shù)名,[1]-參數(shù),多個(gè)參數(shù)使用數(shù)組'subName' => ['date', 'Y-m-d'],//保存根路徑'rootPath' => './Uploads/',// 保存路徑'savePath' => '',// 上傳文件命名規(guī)則,[0]-函數(shù)名,[1]-參數(shù),多個(gè)參數(shù)使用數(shù)組'saveName' => ['uniqid', ''],// 文件保存后綴,空則使用原后綴'saveExt' => '',// 存在同名是否覆蓋'replace' => false,// 是否生成hash編碼'hash' => true,// 檢測(cè)文件是否存在回調(diào),如果存在返回文件信息數(shù)組'callback' => false,// 文件上傳驅(qū)動(dòng)e,'driver' => '',// 上傳驅(qū)動(dòng)配置'driverConfig' => [],];總結(jié)
以上是生活随笔為你收集整理的Webupload+PHP上传大文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【踩坑专栏】Test测试类Class N
- 下一篇: utorrent开机自启动