PHP和AJAX上傳文件

寫這篇文章主要是不要忘記,而且這種上傳還很簡單

第一步在視圖頁面引入兩個JS。jquery.js 和 ajaxupload.js

<script type="text/javascript" src="<? echo URL_PATH; ?>static/admin/js/jquery-1.7.2.js"></script>
<script type="text/javascript" src="<? echo URL_PATH; ?>static/admin/js/ajaxupload.js"></script>

第二步寫個JS

<script type="text/javascript">
$(document).ready(function(){
	//圖片上傳
	new AjaxUpload('#select',{
	    action : '<?php echo URL_PATH . 'comm/upload_img'; ?>',
	    onSubmit : function(){
		   $("#select").attr("value","上傳中...");
		   this.disable();
		},
		onComplete : function(file,ext){
			alert(ext);
	       var obj=eval('('+ext+')');
		   if(obj.error==1){
				alert(obj.url);
		   }
		   else{
		      $("#litpic").attr("value",obj.url);
		   }
		   $("#select").attr("value","上傳");
		   this.enable();
		}
	  }
	);
	
});
</script>
如果看不懂的可以網上搜索ajaxupload.js這個JS ,裏面有詳細的說明。

第三步在相應的處理上傳文件的PHP文件中處裏這個JS提交的action。這裏我要介紹這個PHP上傳類

class Uploader
{
    private $fileField;            //文件域名
    private $file;                 //文件上傳對象
    private $config;               //配置信息
    private $oriName;              //原始文件名
    private $fileName;             //新文件名
    private $fullName;             //完整文件名,即從當前配置目錄開始的URL
	private $UrlName;			   //文件名的URL形式
    private $fileSize;             //文件大小
    private $fileType;             //文件類型
    private $stateInfo;            //上傳狀態信息,
    private $stateMap = array(    //上傳狀態映射表,國際化用戶需考慮此處數據的國際化
        "SUCCESS" ,                //上傳成功標記,在UEditor中內不可改變,否則flash判斷會出錯
        "文件大小超出 upload_max_filesize 限制" ,
        "文件大小超出 MAX_FILE_SIZE 限制" ,
        "文件未被完整上傳" ,
        "沒有文件被上傳" ,
        "上傳文件爲空" ,
        "POST" => "文件大小超出 post_max_size 限制" ,
        "SIZE" => "文件大小超出網站限制" ,
        "TYPE" => "不允許的文件類型" ,
        "DIR" => "目錄創建失敗" ,
        "IO" => "輸入輸出錯誤" ,
        "UNKNOWN" => "未知錯誤" ,
        "MOVE" => "文件保存時出錯"
    );

    /**
     * 構造函數
     * @param string $fileField 表單名稱
     * @param array $config  配置項
     * @param bool $base64  是否解析base64編碼,可省略。若開啓,則$fileField代表的是base64編碼的字符串表單名
     */
    public function __construct( $fileField , $config , $base64 = false )
    {
        $this->fileField = $fileField;
        $this->config = $config;
        $this->stateInfo = $this->stateMap[ 0 ];
        $this->upFile( $base64 );
    }

    /**
     * 上傳文件的主處理方法
     * @param $base64
     * @return mixed
     */
    private function upFile( $base64 )
    {
        //處理base64上傳
        if ( "base64" == $base64 ) {
            $content = $_POST[ $this->fileField ];
            $this->base64ToImage( $content );
            return;
        }

        //處理普通上傳
        $file = $this->file = $_FILES[ $this->fileField ];
        if ( !$file ) {
            $this->stateInfo = $this->getStateInfo( 'POST' );
            return;
        }
        if ( $this->file[ 'error' ] ) {
            $this->stateInfo = $this->getStateInfo( $file[ 'error' ] );
            return;
        }
        if ( !is_uploaded_file( $file[ 'tmp_name' ] ) ) {
            $this->stateInfo = $this->getStateInfo( "UNKNOWN" );
            return;
        }

        $this->oriName = $file[ 'name' ];
        $this->fileSize = $file[ 'size' ];
        $this->fileType = $this->getFileExt();

        if ( !$this->checkSize() ) {
            $this->stateInfo = $this->getStateInfo( "SIZE" );
            return;
        }
        if ( !$this->checkType() ) {
            $this->stateInfo = $this->getStateInfo( "TYPE" );
            return;
        }
        $this->fullName = $this->getFolder() . '/' . $this->getName();
		$this->UrlName .= '/' . $this->fileName;
        if ( $this->stateInfo == $this->stateMap[ 0 ] ) {
            if ( !move_uploaded_file( $file[ "tmp_name" ] , $this->fullName ) ) {
                $this->stateInfo = $this->getStateInfo( "MOVE" );
            }
        }
    }

    /**
     * 處理base64編碼的圖片上傳
     * @param $base64Data
     * @return mixed
     */
    private function base64ToImage( $base64Data )
    {
        $img = base64_decode( $base64Data );
        $this->fileName = time() . rand( 1 , 10000 ) . ".png";
        $this->fullName = $this->getFolder() . '/' . $this->fileName;
        if ( !file_put_contents( $this->fullName , $img ) ) {
            $this->stateInfo = $this->getStateInfo( "IO" );
            return;
        }
        $this->oriName = "";
        $this->fileSize = strlen( $img );
        $this->fileType = ".png";
    }

    /**
     * 獲取當前上傳成功文件的各項信息
     * @return array
     */
    public function getFileInfo()
    {
        return array(
            "originalName" => $this->oriName ,
            "name" => $this->fileName ,
            "baseName" => $this->fullName ,
			"urlName" => $this->UrlName ,
            "size" => $this->fileSize ,
            "type" => $this->fileType ,
            "state" => $this->stateInfo
        );
    }

    /**
     * 上傳錯誤檢查
     * @param $errCode
     * @return string
     */
    private function getStateInfo( $errCode )
    {
        return !$this->stateMap[ $errCode ] ? $this->stateMap[ "UNKNOWN" ] : $this->stateMap[ $errCode ];
    }

    /**
     * 重命名文件
     * @return string
     */
    private function getName()
    {
        return $this->fileName = time() . rand( 1 , 10000 ) . $this->getFileExt();
    }

    /**
     * 文件類型檢測
     * @return bool
     */
    private function checkType()
    {
        return in_array( $this->getFileExt() , $this->config[ "allowFiles" ] );
    }

    /**
     * 文件大小檢測
     * @return bool
     */
    private function  checkSize()
    {
        return $this->fileSize <= ( $this->config[ "maxSize" ] * 1024 );
    }

    /**
     * 獲取文件擴展名
     * @return string
     */
    private function getFileExt()
    {
        return strtolower( strrchr( $this->file[ "name" ] , '.' ) );
    }

    /**
     * 按照日期自動創建存儲文件夾
     * @return string
     */
    private function getFolder()
    {
        $pathStr = $this->config[ "savePath" ];
        if ( strrchr( $pathStr , "/" ) != "/" ) {
            $pathStr .= "/";
        }
        $pathStr .= date( "Ymd" );
        if ( !file_exists( $pathStr ) ) {
            if ( !mkdir( $pathStr , 0777 , true ) ) {
                return false;
            }
        }
		$this->UrlName .= $this->config['saveUrl'] . date( "Ymd" );
        return $pathStr;
    }
}
使用這個類用如下方式

//上傳配置
		$config = array(
			"saveUrl" => URL_PATH . "attached/" , 
			"savePath" => ROOT_PATH . "/attached/" , //保存路徑
			"allowFiles" => array('.gif', '.jpg', '.jpeg', '.png', '.bmp' ) , //文件允許格式
			"maxSize" => 2000 //文件大小限制,單位KB
		);
		//生成上傳實例對象並完成上傳
		$up = new Uploader( "userfile" , $config );
		$info = $up->getFileInfo();

然後返回到AJAX的JS處理上傳。


發佈了48 篇原創文章 · 獲贊 16 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章