大文件webuploader的基本使用

webuploader的簡單使用javascript

須要的文件   自備  百度不少php

webuploader.js  uploader.swf  jQuery 

HTML代碼css

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
	<script type="text/javascript" src="webuploader.js"></script>
	<style type="text/css">
      .webuploader-container {
			position: relative;
		}
		.webuploader-element-invisible {
			position: absolute !important;
			clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
		    clip: rect(1px,1px,1px,1px);
		}
		.webuploader-pick {
			position: relative;
			display: inline-block;
			cursor: pointer;
			background: #00b7ee;
			padding: 10px 15px;
			color: #fff;
			text-align: center;
			border-radius: 3px;
			overflow: hidden;
		}
		.webuploader-pick-hover {
			background: #00a2d4;
		}

		.webuploader-pick-disable {
			opacity: 0.6;
			pointer-events:none;
		}
	</style>
</head>
<body>
	<div id="uploader" class="wu-example">
		 <!--用來存放文件信息-->
		 <div id="thelist" class="uploader-list"></div>
		 <div class="btns">
		    <div id="picker">選擇文件</div>
		    <button id="ctlBtn" class="btn btn-default">開始上傳</button>
		 </div>
	 </div>
	 <div id="fileList"></div>
	 <div id="ss"></div>
</body>
</html>

  JavaScript代碼html

<script type="text/javascript">
	jQuery(function() {
	    var  uploader;
	    uploader = WebUploader.create({
			   resize: false, // 不壓縮image	   
			   swf: 'uploader.swf',// swf文件路徑	  
			   server: 'upload.php', // 文件接收服務端。  
			   pick: '#picker',// 選擇文件的按鈕。可選。內部根據當前運行是建立,多是input元素,也多是flash.
			   chunked: true,//容許分片上傳
			   chunkSize:2*1024*1024,//每一個分片大小
			   auto: true,//是否自動上傳
			   duplicate:true,//去除重複
			   fileNumLimit:20,//上傳文件個數限制   
		       fileSingleSizeLimit:20*1024*1024, //單個文件大小限制  20M
			   accept: {
			    title: '文字描述',//文字描述
			    extensions: 'png,3gp,mp4,rmvb,mov,avi,m4v,wmv',//上傳文件後綴
			    mimeTypes: 'image/*,video/*,audio/*,application/*'//上傳文件類型
			   }
		});
		uploader.on('uploadStart', function (file) {
              alert("這是文件上傳前的操做函數");
        });
        $("#ctlBtn").click(function () {
        	alert("要使用手動上傳請設置參數");
          //  uploader.upload();//這是將參數配置auto設置 false 手動上傳
        });
        uploader.on( 'fileQueued', function( file ) { //文件加入隊列後觸發
			 var $list = $("#fileList"), 
			 $li = $( 
			 '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>'+ '<div class="info">' + file.name + '</div>' + '</div>'
			 ), 
			 $img = $li.find('img'); 		  
			 // $list爲容器jQuery實例 
			 $list.append( $li );   
			 // 建立縮略圖 
			 uploader.makeThumb( file, function( error, src ) { //src base_64位
				 if ( error ) { 
					 $img.replaceWith('<span>不能預覽</span>'); 
					 return; 
			     } 
			  
			     $img.attr( 'src', src ); 
			 }, 100, 100 ); //100x100爲縮略圖尺寸 
		});
		// 文件上傳過程當中建立進度實時顯示。 
		uploader.on( 'uploadProgress', function( file, percentage ) { 
			var ss=(percentage*100)+"%";
			$("#ss").text(ss);
		}); 
		  
		// 文件上傳成功
		uploader.on( 'uploadSuccess', function( file, res ) { 
			 alert("這是文件上傳成功的操做函數");
			 console.log(res.filePaht);//這裏能夠獲得上傳後的文件路徑 
		}); 

	});
</script>

  PHP代碼java

<?php

/**
 * @Author: Administrator
 * @Date:   2017-11-22 17:17:48
 * @Last Modified by:   liao
 * @Last Modified time: 2018-01-16 21:23:29
 */

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");
//字符串轉碼 不管是什麼文件名稱,先unicode轉utf8 unicode轉utf8 注意$str='"..."',內部雙引號,外部單引號 對於變量$str='..',咱們須要處理'"'.$str.'"',處理後成一個新變量
function unicode2utf8($str){
  if(!$str) return $str;
  $decode = json_decode($str);
  if($decode) return $decode;
  $str = '["' . $str . '"]';
  $decode = json_decode($str);
  if(count($decode) == 1){
  return $decode[0];
  }
  return $str;
}  
 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; // 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 = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
  $targetDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material_tmp';
  $uploadDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material';
  $cleanupTargetDir = true; // Remove old files
  $maxFileAge = 5 * 3600; // Temp file age in seconds
  // Create target dir
  if (!file_exists($targetDir)) {
   @mkdir($targetDir);
  }
  // Create target dir
  if (!file_exists($uploadDir)) {
   @mkdir($uploadDir);
  }
  // Get a file name
  if (isset($_REQUEST["name"])) {
   $fileName = $_REQUEST["name"];
  } elseif (!empty($_FILES)) {
   $fileName = $_FILES["file"]["name"];
  } else {
   $fileName = uniqid("file_");
  }
  //-------------------------------------------------------
    $fileName=unicode2utf8('"'.$fileName.'"');
    $fileName= iconv("UTF-8", "GBK", $fileName);//防止fopen語句失效
    //-----------------------------------------------------------------------
  $oldName = $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 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");
  $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.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'],
    ];
 
   echo json_encode($response);
   exit();
  }
 
  // Return Success JSON-RPC response
  die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');

?>

  這裏是webuploader  裏面的使用方法jquery

相關文章
相關標籤/搜索