上傳文件(FineUploader)插件

插件下載地址:http://pan.baidu.com/s/1mhqRCyk(表示雖然有官網,但是官網的貌似不對)

Fine Uploader特點如下
Fine Uploader Features: 
A:支持文件上傳進度顯示. 
B:文件拖拽瀏覽器上傳方式 
C:Ajax頁面無刷新. 
D:多文件上傳. 
F:跨瀏覽器. 
E:跨後臺服務器端語言. 

qq.FineUploader對象還有如下控制參數:

validation:該參數一般用來在執行上傳文件操作前.在客戶端做一些驗證.驗證操作包含文件格式.文件大小.等添加格式如下:

   1:   validation: 
   2:    {
   3:          allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
   4:          sizeLimit: 204800 // 200 kB = 200 * 1024 bytes
   5:    }

allowedExtensions控制上傳文件的後綴格式數組.

sizeLimit上傳文件大小的上限,單位爲byte的數值.瀏覽器不一定支持本設置.也可以在服務器端裏設置.

minSizeLimit:上傳文件大小的下限,單位爲byte的數值.同上有些瀏覽器存在適配問題.建議統一在服務端設置.

另外針對qq.FineUploder對象在執行上傳操作整個過程.定義了五個客戶端可控做額外操作的事件.可以再callback參數下設置定義:

   1:  callbacks: 
   2:  {
   3:          onSubmit: function(id, fileName) {
   4:            $messages.append('<div id="file-' + id + '" class="alert" style="margin: 20px 0 0"></div>');
   5:          },
   6:          onUpload: function(id, fileName) {
   7:            $('#file-' + id).addClass('alert-info')
   8:                            .html('<img src="client/loading.gif" alt="Initializing. Please hold."> ' +
   9:                            'Initializing ' +
  10:                            '“' + fileName + '”');
  11:          }
  12:  }

onSubmit事件:文件開始提交.調用參數格式如下:onSubmit:  function(id,  fileName)  {}.

onUpload事件: 文件開始上傳.調用參數格式如下:onUpload: function(id, fileName) {}.

onProgress事件: 文件正在上傳.調用參數格式如下:onProgress:  function(id,  fileName,  loaded,  total)  {}.

onComplete事件: 文件上傳成功. 調用參數格式如下:onComplete:  function(id,  fileName,  responseJSON)  {}.

onCancel事件: 取消文件上傳.調用參數格式如下:onCancel:  function(id,  fileName)  {}.

如上五個事件基本覆蓋整個上傳文件操作中所有過程.完全以開放的形式可以再客戶端操作.關於調用如上事件參數說明如下:

Id:表示第幾個開始上傳的文件.Fine Uploder定義是默認從0開始計數.

fileName:上傳文件的文件名.

loaded:表示已經上傳到服務器端數據的大小[byte].

total: 需要上傳文件的大小.

responseJSON: 用來在上傳操作完成後返回的Json格式的數據.通過Jquery反序列化出來對象.其中包含一個IsSuccess屬性用來判斷此次上傳是否成功.

如果你想在上傳過程向服務器端傳遞數據.可以通過如下參數控制:

params:用來向服務器端傳遞數據.注意params採用key-value的數組存儲.採用Post方式發送給服務器端.一般傳遞參數格式如下:

   1:    params: 
   2:    {                
   3:        argument1: "value1",                
   4:        argument2: "value2"                
   5:    },

ok.這時基本關於Fine Uploader客戶端初始化和控制操作選項基本完成.當我們需要上傳操作時.如果IsAuto=false時可以通過已經定義qq.FineUploader對象的uploadStoreFiles()方式手工觸發上傳操作:

   1:  $('#triggerUpload').click(function() {
   2:          uploader2.uploadStoredFiles();
   3:      });
如果我們此時點擊上傳會發現.則提示上傳失敗. 因爲還沒有對上傳服務器端做任何處理:
   1:    request: 
   2:      {
   3:          endpoint: 'server/handlerfunction'
   4:      },

這時我們需要在EndPoint指定處理文件上傳的Php文件[這裏是phpdemo]


index.html

<!DOCTYPE html>
<html>
<head>
	<title>上傳文件測試</title>
	<link href="fine-uploader/fineuploader-new.css" rel="stylesheet">
<!-- 	<link href="fine-uploader/bootstrap.min.css" rel="stylesheet"> -->
	<script src="fine-uploader/fine-uploader.min.js"></script>
	<script type="text/template" id="qq-template">
        <div class="qq-uploader-selector qq-uploader" qq-drop-area-text="Drop files here">
            <div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
                <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
            </div>
            <div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
                <span class="qq-upload-drop-area-text-selector"></span>
            </div>
            <div class="qq-upload-button-selector qq-upload-button">
                <div>Upload a file</div>
            </div>
            <span class="qq-drop-processing-selector qq-drop-processing">
                <span>Processing dropped files...</span>
                <span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
            </span>
            <ul class="qq-upload-list-selector qq-upload-list" aria-live="polite" aria-relevant="additions removals">
                <li>
                    <div class="qq-progress-bar-container-selector">
                        <div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
                    </div>
                    <span class="qq-upload-spinner-selector qq-upload-spinner"></span>
                    <img class="qq-thumbnail-selector" qq-max-size="100" qq-server-scale>
                    <span class="qq-upload-file-selector qq-upload-file"></span>
                    <span class="qq-edit-filename-icon-selector qq-edit-filename-icon" aria-label="Edit filename"></span>
                    <input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
                    <span class="qq-upload-size-selector qq-upload-size"></span>
                    <button type="button" class="qq-btn qq-upload-cancel-selector qq-upload-cancel">Cancel</button>
                    <button type="button" class="qq-btn qq-upload-retry-selector qq-upload-retry">Retry</button>
                    <button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete">Delete</button>
                    <span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
                </li>
            </ul>

            <dialog class="qq-alert-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">Close</button>
                </div>
            </dialog>

            <dialog class="qq-confirm-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">No</button>
                    <button type="button" class="qq-ok-button-selector">Yes</button>
                </div>
            </dialog>

            <dialog class="qq-prompt-dialog-selector">
                <div class="qq-dialog-message-selector"></div>
                <input type="text">
                <div class="qq-dialog-buttons">
                    <button type="button" class="qq-cancel-button-selector">Cancel</button>
                    <button type="button" class="qq-ok-button-selector">Ok</button>
                </div>
            </dialog>
        </div>
    </script>
</head>
<body>
	<div id="fine-uploader"></div>
    <script>
        var uploader = new qq.FineUploader({
            debug: true,
            element: document.getElementById('fine-uploader'),
            request: {
                endpoint: 'uploadhandler.php'
            },
            deleteFile: {
                enabled: true,
                endpoint: ''
            },
            retry: {
               enableAuto: true
            },
            callbacks:{
            	onComplete:  function(id,  fileName,  responseJSON)  {
            		console.log(responseJSON);
            	}
            }
        });
    </script>
</body>
</html>


php上傳文件的地址:

<?php
require_once 'fileUpload.php';
$uploader = new fileUpload();
$status = false;
$allowedExtensions = array("jpeg", "jpg", "bmp", "png", "pdf");
$uploader->set('fileType',$allowedExtensions);
$uploader->set('maxsize',100 * 1024 * 1024);
if($uploader->upload('qqfile')){
	$status = true;
}else{
	$status = false;
}
$result = array('filename'=>$uploader->getFileName(),
				'error'=>$uploader->getErrorMsg(),
				'success'=>$status    <span style="color:#ff0000;">//success一定要返回false或者true,而且返回的json數據裏面一定要寫上,否則插件會認爲上傳不成功,會自動多次上傳</span>
	);
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
// echo json_encode($_FILES);
?>


php上傳文件的類:

<?php
class FileUpload { 
    private $path = "./uploads";          //上傳文件保存的路徑
    private $allowtype = array('jpg','gif','png'); //設置限制上傳文件的類型
    private $maxsize = 1000000;           //限制文件上傳大小(字節)
    private $israndname = true;           //設置是否隨機重命名文件, false不隨機
  
    private $originName;              //源文件名
    private $tmpFileName;              //臨時文件名
    private $fileType;               //文件類型(文件後綴)
    private $fileSize;               //文件大小
    private $newFileName;              //新文件名
    private $errorNum = 0;             //錯誤號
    private $errorMess="";             //錯誤報告消息
  
    /**
     * 用於設置成員屬性($path, $allowtype,$maxsize, $israndname)
     * 可以通過連貫操作一次設置多個屬性值
     *@param  string $key  成員屬性名(不區分大小寫)
     *@param  mixed  $val  爲成員屬性設置的值
     *@return  object     返回自己對象$this,可以用於連貫操作
     */
    function set($key, $val){
		$key = strtolower($key); 
		if( array_key_exists( $key, get_class_vars(get_class($this) ) ) ){
			$this->setOption($key, $val);
		}
		return $this;
    }
  
    /**
     * 調用該方法上傳文件
     * @param  string $fileFile  上傳文件的表單名稱 
     * @return bool        如果上傳成功返回數true 
     */
  
    function upload($fileField) {
		$return = true;
		/* 檢查文件路徑是滯合法 */
		if( !$this->checkFilePath() ) {       
			$this->errorMess = $this->getError();
			return false;
		}
		/* 將文件上傳的信息取出賦給變量 */
		$name = $_FILES[$fileField]['name'];
		$tmp_name = $_FILES[$fileField]['tmp_name'];
		$size = $_FILES[$fileField]['size'];
		$error = $_FILES[$fileField]['error'];

		/* 如果是多個文件上傳則$file["name"]會是一個數組 */
		if(is_Array($name)){    
			$errors=array();
			/*多個文件上傳則循環處理 , 這個循環只有檢查上傳文件的作用,並沒有真正上傳 */
			for($i = 0; $i < count($name); $i++){ 
			  /*設置文件信息 */
			  	if($this->setFiles($name[$i],$tmp_name[$i],$size[$i],$error[$i] )) {
					if(!$this->checkFileSize() || !$this->checkFileType()){
					  $errors[] = $this->getError();
					  $return=false; 
					}
			  	}else{
			    	$errors[] = $this->getError();
			    	$return=false;
			  	}
			  	/* 如果有問題,則重新初使化屬性 */
			  	if(!$return)          
			    	$this->setFiles();
			}

			if($return){
				  /* 存放所有上傳後文件名的變量數組 */
				$fileNames = array();      
				/* 如果上傳的多個文件都是合法的,則通過銷魂循環向服務器上傳文件 */
				for($i = 0; $i < count($name); $i++){ 
				    if($this->setFiles($name[$i], $tmp_name[$i], $size[$i], $error[$i] )) {
				    	$this->setNewFileName(); 
				      	if(!$this->copyFile()){
				        	$errors[] = $this->getError();
				        	$return = false;
				      	}
				      	$fileNames[] = $this->newFileName;  
				    }          
				}
				$this->newFileName = $fileNames;
			}
			$this->errorMess = $errors;
			return $return;
				/*上傳單個文件處理方法*/
		} else {
			/* 設置文件信息 */
			if($this->setFiles($name,$tmp_name,$size,$error)) {
			  /* 上傳之前先檢查一下大小和類型 */
			  	if($this->checkFileSize() && $this->checkFileType()){ 
			    /* 爲上傳文件設置新文件名 */
			    	$this->setNewFileName(); 
			    /* 上傳文件  返回0爲成功, 小於0都爲錯誤 */
			    	if($this->copyFile()){ 
			      		return true;
			    	}else{
			      		$return=false;
			    	}
			  	}else{
			    	$return=false;
			  	}
			} else {
			  	$return=false; 
			}
			//如果$return爲false, 則出錯,將錯誤信息保存在屬性errorMess中
			if(!$return)
			  	$this->errorMess = $this->getError();  
			return $return;
		}
    }
  
    /** 
     * 獲取上傳後的文件名稱
     * @param  void   沒有參數
     * @return string 上傳後,新文件的名稱, 如果是多文件上傳返回數組
     */
    public function getFileName(){
      	return $this->newFileName;
    }
  
    /**
     * 上傳失敗後,調用該方法則返回,上傳出錯信息
     * @param  void   沒有參數
     * @return string  返回上傳文件出錯的信息報告,如果是多文件上傳返回數組
     */
    public function getErrorMsg(){
      	return $this->errorMess;
    }
  
    /* 設置上傳出錯信息 */
    private function getError() {
      	$str = "上傳文件<font color='red'>" . $this->originName . "</font>時出錯 : ";
      	switch ($this->errorNum) {
        	case 4: $str .= "沒有文件被上傳"; break;
        	case 3: $str .= "文件只有部分被上傳"; break;
        	case 2: $str .= "上傳文件的大小超過了HTML表單中MAX_FILE_SIZE選項指定的值"; break;
        	case 1: $str .= "上傳的文件超過了php.ini中upload_max_filesize選項限制的值"; break;
        	case -1: $str .= "未允許類型"; break;
        	case -2: $str .= "文件過大,上傳的文件不能超過{$this->maxsize}個字節"; break;
        	case -3: $str .= "上傳失敗"; break;
        	case -4: $str .= "建立存放上傳文件目錄失敗,請重新指定上傳目錄"; break;
        	case -5: $str .= "必須指定上傳文件的路徑"; break;
        	default: $str .= "未知錯誤";
      	}
      	return $str.'<br>';
    }
  
    /* 設置和$_FILES有關的內容 */
    private function setFiles($name="", $tmp_name="", $size=0, $error=0) {
	    $this->setOption('errorNum', $error);
	    if($error)
	        return false;
	    $this->setOption('originName', $name);
	    $this->setOption('tmpFileName',$tmp_name);
	    $aryStr = explode(".", $name);
	    $this->setOption('fileType', strtolower($aryStr[count($aryStr)-1]));
	    $this->setOption('fileSize', $size);
	    return true;
    }
  
    /* 爲單個成員屬性設置值 */
    private function setOption($key, $val) {
      	$this->$key = $val;
    }
  
    /* 設置上傳後的文件名稱 */
    private function setNewFileName() {
		if ($this->israndname) {
			$this->setOption('newFileName', $this->proRandName());
		} else{ 
			$this->setOption('newFileName', $this->originName);
		} 
    }
  
    /* 檢查上傳的文件是否是合法的類型 */
    private function checkFileType() {
		if (in_array(strtolower($this->fileType), $this->allowtype)) {
			return true;
		}else {
			$this->setOption('errorNum', -1);
			return false;
		}
    }
  
    /* 檢查上傳的文件是否是允許的大小 */
    private function checkFileSize() {
		if ($this->fileSize > $this->maxsize) {
			$this->setOption('errorNum', -2);
			return false;
		}else{
			return true;
		}
    }
  
    /* 檢查是否有存放上傳文件的目錄 */
    private function checkFilePath() {
		if(empty($this->path)){
			$this->setOption('errorNum', -5);
			return false;
		}
		if (!file_exists($this->path) || !is_writable($this->path)) {
			if (!@mkdir($this->path, 0755)) {
		  		$this->setOption('errorNum', -4);
		  		return false;
			}
		}
		return true;
    }
  
    /* 設置隨機文件名 */
    private function proRandName() {    
      $fileName = date('YmdHis')."_".rand(100,999);    
      return $fileName.'.'.$this->fileType; 
    }
  
    /* 複製上傳文件到指定的位置 */
    private function copyFile() {
		if(!$this->errorNum) {
			$path = rtrim($this->path, '/').'/';
			$path .= $this->newFileName;
			if (@move_uploaded_file($this->tmpFileName, $path)) {
		  		return true;
			}else{
		  		$this->setOption('errorNum', -3);
		  		return false;
			}
		} else {
			return false;
		}
    }
}
?>




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