Upload.class.php 1.94 KB
<?php
require_once 'qiniu/io.php';
require_once 'qiniu/rs.php';

/**
 * 七牛上传
 */
class Util_Qiniu_Upload
{
	/**
	 * 初始化key
	 * 
	 * @param string $accessKey
	 * @param string $secretKey
	 */
	public static function initKey($accessKey, $secretKey)
	{
		Qiniu_SetKeys($accessKey, $secretKey);
	}
		
	/**
	 * 上传文件
	 * 
	 * @param string $bucket
	 * @param string $key
	 * @param string $fileName
	 * @return boolean
	 */
	public static function upload($bucket, $key, $fileName)
	{
		$upToken = self::getToken($bucket);
		$putExtra = new Qiniu_PutExtra();
		$putExtra->Crc32 = 1;
		list($ret, $err) = Qiniu_PutFile($upToken, $key, $fileName, $putExtra);
		//上传文件
		if(empty($err))
		{
			return true;
		}
		else 
		{
	
			return false;
		}
	}
	
	/**
	 * 上传文件流方式
	 * 
	 * @param string $bucket
	 * @param string $key
	 * @param string $fileStream
	 * @return boolean
	 */
	public static function uploadStream($bucket, $key, $fileStream)
	{
		$putPolicy = new Qiniu_RS_PutPolicy($bucket);
		$upToken = $putPolicy->Token(null);
		list($ret, $err) = Qiniu_Put($upToken, $key, $fileStream, null);
		if(empty($err))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * 获取token
	 * 
	 * @param string $bucket
	 * @param array $params
	 * @return string
	 */
	public static function getToken($bucket, $params  = array())
	{
		$putPolicy = new Qiniu_RS_PutPolicy($bucket);
		if(!empty($params))
		{
			$vars = get_class_vars(get_class($putPolicy));
			$classVars = array_intersect_key($params, $vars);
			foreach($classVars as $key => $var)
			{
				$putPolicy->$key = $var;
			}
		}
		return $putPolicy->Token(null);
	}
	
	/**
	 * 删除
	 * 
	 * @param string $bucket
	 * @param string $key
	 * @return boolean
	 */
	public static function delete($bucket, $key)
	{
		$client = new Qiniu_MacHttpClient(null);
		$err = Qiniu_RS_Delete($client, $bucket, $key);
		if(empty($err))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}