PHP阿里云OSS,七牛云 上传文件

WBOY
Release: 2016-06-23 13:31:06
Original
1306 people have browsed it

来源:

七牛云

PHPSDK下载:http://pan.baidu.com/s/1o69TGcM

7.X版本:

DEMO:

<?phprequire_once './vendor/autoload.php'; use Qiniu\Auth;use Qiniu\Storage\BucketManager;use Qiniu\Storage\UploadManager; $accessKey = 'accessKey';$secretKey = 'secretKey';$auth = new Auth($accessKey, $secretKey); $bucketMgr = New BucketManager($auth);$bucket = 'wsy100';$key = 'QQ图片20150604131612.png'; //文件删除/* $err = $bucketMgr->delete($bucket, $key);if ($err !== null) {    var_dump($err);} else {    echo 'delete ok';} *//*  * 单个文件 * list($ret, $err) = $bucketMgr->stat($bucket, $key);echo "\n====> stat result: \n";if ($err !== null) {    var_dump($err);} else {    var_dump($ret);} */$token = $auth->uploadToken($bucket);$uploadMgr = New UploadManager(); list($ret, $err) = $uploadMgr->putFile($token, time().'.jpg', 'C:\Users\Administrator\Pictures\images\20150604131612.png');echo "\n====> putFile result: \n";if ($err !== null) {    var_dump($err);} else {    print_r($ret);}
Copy after login


上传远程URL文件:

$url='http://img.hb.aicdn.com/b3ddfada312d19dc0be9f17f9ca497767cb657871f50a-Hj44uu_fw658';$ret=$bucketMgr->fetch($url, $bucket, $key);print_r($ret);
Copy after login

2.获取bucket所有文件

list($items, $marker, $err) = $bucketMgr->listFiles($bucket, $prefix = null, $marker = null, $limit = 1000, $delimiter = null);echo "\n====> List result: \n";if ($err !== null) {    var_dump($err);} else {    echo "Marker: $marker\n";    echo 'items====>\n';    print_r($items);    //echo (string)$items[10]['putTime'];    //echo strtotime($items[10]['putTime']);}
Copy after login

3.删除文件

$err = $bucketMgr->delete($bucket, $key);if ($err !== null) {    var_dump($err);} else {    echo 'delete ok';}
Copy after login

4.获取单个文件信息

list($ret, $err) = $bucketMgr->stat($bucket, $key);echo "\n====> stat result: \n";if ($err !== null) {    var_dump($err);} else {    print_r($ret);}
Copy after login

5.文件上传

$token = $auth->uploadToken($bucket);$uploadMgr = New UploadManager(); list($ret, $err) = $uploadMgr->putFile($token, date('Y-m-d-H-i-s',time()).'.jpg', 'C:\Users\Administrator\Pictures\20150504194317.png');echo "\n====> putFile result: \n";if ($err !== null) {    var_dump($err);} else {    print_r($ret);}
Copy after login

puttime Epoch时间戳的转换

$puttime=substr(str_replace('.', '','1.4357550505488E+16'),0,10);echo $puttime;
Copy after login

trim替换也可以,暂时没找到系统函数转换,也可以除10000000

OR

$puttime=date('Y-m-d H:i:s',1.4357550505488E+16/10000000);
Copy after login

上传策略生成:

$data['scope']='wsy100';$data['deadline']=time()+3600;$encoded=urlsafe_base64_encode(json_encode($data));$signature=hash_hmac('sha1',$encoded,'KEY',true);$encode_signed = urlsafe_base64_encode($signature);$UploadToken='AK:'.$encode_signed.':'.$encoded; echo $UploadToken; /* 第三步:对json序列化后的上传策略进行URL安全的Base64编码,得到如下encoded:eyJzY29wZSI6IndzeTEwMCIsImRlYWRsaW5lIjoxNDM1ODE3NzA5fQ==第四步:用SecretKey对编码后的上传策略进行HMAC-SHA1加密,并且做URL安全的Base64编码,得到如下的encoded_signed:Yu1NpdDvbM1NPr4IxTFsMBLxDQc=第五步:将 AccessKey、encode_signed 和 encoded 用 “:” 连接起来,得到如下的UploadToken:*/ function urlsafe_base64_encode($data) {    $data = base64_encode($data);    $data = str_replace(array('+','/'),array('-','_'),$data);    return $data;}
Copy after login


写完才知道有现成的

$token = $auth->uploadToken($bucket);
Copy after login

可以用。权当练手了吧

ajax上传预览见:

DEMO:http://t.zy62.com/wx.php/Index/upload

API:http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html

6.X版本

6.x版本没有fetch获取远程URL资源上传的方法,封装了个.

七牛文档:http://developer.qiniu.com/docs/v6/sdk/legacy-php-sdk.html

封装好的下载地址:http://pan.baidu.com/s/1gdu95yb

在qiniu/conf.php 15行后加了:

$QINIU_FETCH_HOST='http://iovip.qbox.me';//fetch  URL
Copy after login

rsf.php末尾增加:

/** * 从指定URL抓取资源,并将该资源存储到指定空间中 * * @param $url 指定的URL        	 * @param $bucket 目标资源空间        	 * @param $key 目标资源文件名        	 * * @return array[] 包含已拉取的文件信息。 *         成功时: [ *         [ *         "hash" => "<Hash string>", *         "key" => "<Key string>" *         ], *         null *         ] *         *         失败时: [ *         null, *         Qiniu/Http/Error *         ] * @link http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html */function Qiniu_Fetch($self,$url, $bucket, $key) {	global $QINIU_FETCH_HOST;	$resource = base64_urlSafeEncode ( $url );	$to = entry ( $bucket, $key );	$url = $QINIU_FETCH_HOST . '/fetch/' . $resource . '/to/' . $to;	return Qiniu_Client_Call ( $self, $url );}/** * 计算七牛API中的数据格式 * * @param $bucket 待操作的空间名        	 * @param $key 待操作的文件名        	 * * @return 符合七牛API规格的数据格式 * @link http://developer.qiniu.com/docs/v6/api/reference/data-formats.html */function entry($bucket, $key) {	$en = $bucket;	if (! empty ( $key )) {		$en = $bucket . ':' . $key;	}	return base64_urlSafeEncode ( $en );}/** * 对提供的数据进行urlsafe的base64编码。 * * @param string $data 待编码的数据,一般为字符串 * * @return string 编码后的字符串 * @link http://developer.qiniu.com/docs/v6/api/overview/appendix.html#urlsafe-base64 */function base64_urlSafeEncode($data){	$find = array('+', '/');	$replace = array('-', '_');	return str_replace($find, $replace, base64_encode($data));}
Copy after login


使用方法:

Qiniu_Fetch($client,'http://phpcto.b0.upaiyun.com/courselesson/3/2015104031642-h23061.mp4',$bucket,time().'.mp4');
Copy after login

获取所有文件信息:

<?phprequire_once("qiniu/rs.php");require_once("qiniu/rsf.php");$bucket = 'wsy100';$key = "qqConnect_Server_SDK_php_v2.0.zip";$accessKey = '';$secretKey = ''; Qiniu_SetKeys($accessKey, $secretKey);$client = new Qiniu_MacHttpClient(null);$putPolicy = new Qiniu_RS_PutPolicy($bucket);$upToken = $putPolicy->Token(null); //echo $upToken;exit();/* list($ret, $err) = Qiniu_RS_Stat($client, $bucket, $key);echo "Qiniu_RS_Stat result: \n";if ($err !== null) {    print_r($err);} else {    $ret['putTime']=date('Y-m-d H:i:s',$ret['putTime']/10000000);    print_r($ret);} */print_r(Qiniu_RSF_ListPrefix($client,$bucket));
Copy after login


阿里云OSS

获取bucket资源列表

<?phprequire_once './aliyun.php';use \Aliyun\OSS\OSSClient;try {    $client = OSSClient::factory(array(    'AccessKeyId' => '//Your AccessKeyId',    'AccessKeySecret' => 'Your AccessKeySecret',    //在https://ak-console.aliyun.com/获取));$client->createBucket(array(    'Bucket' => 'Your Bucket',));    $objectListing = $client->listObjects(array(    'Bucket' => 'Your Bucket',));foreach ($objectListing->getObjectSummarys() as $objectSummary) {    echo $objectSummary->getKey();}} catch (\Aliyun\OSS\Exceptions\OSSException $ex) {    echo "Error: " . $ex->getErrorCode() . "\n";} catch (\Aliyun\Common\Exceptions\ClientException $ex) {    echo "ClientError: " . $ex->getMessage() . "\n";}
Copy after login

Fatal error: Uncaught exception 'Aliyun\OSS\Exceptions\OSSException' with message 'The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.'解决方案


原因是PHP SDK默认使用杭州节点,而你的bucket非杭州节点,解决方案,在初始化时指定节点.

$client = OSSClient::factory(array(        'AccessKeyId' => 'Your AccessKeyId',        'AccessKeySecret' => 'Your AccessKeySecret',        'Endpoint' => 'http://oss-cn-beijing.aliyuncs.com',//北京节点    ));
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template