概述
阿里云对象存储(Object Storage Service,简称OSS),是阿里云对外提供的海量、安全、低成本、高可靠的云存储服务。用户可以通过调用API,在任何应用、任何时间、任何地点上传和下载数据,也可以通过用户Web控制台对数据进行简单的管理。OSS适合存放任意文件类型,适合各种网站、开发企业及开发者使用。
一、安装方法
1、如果您通过composer管理您的项目依赖,可以在你的项目根目录运行:
$ composer require aliyuncs/oss-sdk-php
或者在你的composer.json中声明对Aliyun OSS SDK for PHP的依赖:
"require": {
"aliyuncs/oss-sdk-php": "~2.0"
}
然后通过composer install安装依赖。composer安装完成后,在您的PHP代码中引入依赖即可:
require_once __DIR__ . '/vendor/autoload.php';
2、下载SDK源码,在您的代码中引入SDK目录下的autoload.php文件:
require_once '/path/to/oss-sdk/autoload.php';
Github地址:https://github.com/aliyun/aliyun-oss-php-sdk;
常用类
类名 | 解释 |
OSS\OssClient | OSS客户端类,用户通过OssClient的实例调用接口 |
OSS\Core\OssException | OSS异常类,用户在使用的过程中,只需要注意这个异常 |
前台上传界面:
<form action="selfUpload.php" enctype="multipart/form-data" method="post">
<input type="file" name="first" />
<input type="submit" value="upload" />
</form>
后台selfUpload.php
<?php
var_dump($_FILES);
//move_uploaded_file($_FILES['first']['tmp_name'],'uploads/aa.png');
echo "ok";
require_once __DIR__ . './../vendor/autoload.php';
use OSS\OssClient;
use OSS\Core\OssException;
$accessKeyId = "txNZbAAZXQYkGg5HXg"; ;
$accessKeySecret = "34RVl1AA2aM4U4dzzn6tZg3ZKjfbOU96";
$endpoint = "oss-cn-hangzhou.aliyuncs.com";
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
} catch (OssException $e) {
print $e->getMessage();
}
$content=$_FILES['first']['tmp_name'];
$object='img/bb.png';
$bucket='wed0525muller';
$ossClient->uploadFile($bucket,$object,$content);
echo "yes";
$ossClient->setConnectTimeout(15); $ossClient->setTimeout(3600); //创建一个叫wed0525muller的bucket $bucket = "wed0525muller"; try { $ossClient->createBucket($bucket); } catch (OssException $e) { print $e->getMessage(); } //往hello文件里写入HI,OSS. $bucket= "wed0525muller"; $object = "hello"; $content = "Hi, OSS."; try { $ossClient->putObject($bucket, $object, $content); } catch (OssException $e) { print $e->getMessage(); } //获得bucket列表 $bucketListInfo = $ossClient->listBuckets(); $bucketList = $bucketListInfo->getBucketList(); foreach($bucketList as $bucket) { print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n<br/>"); }
更具体的请参考阿里云官方文档