AliyunossServer.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: xiaofeng
  5. * Date: 2018/6/11
  6. * Time: 上午9:28
  7. */
  8. namespace common\api;
  9. use Yii;
  10. use yii\base\Component;
  11. use OSS\OssClient;
  12. class AliyunossServer extends Component{
  13. public static $oss;
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. $accessKeyId = Yii::$app->params['aliyunoss']['accessKeyId']; //获取阿里云oss的accessKeyId
  18. $accessKeySecret = Yii::$app->params['aliyunoss']['accessKeySecret']; //获取阿里云oss的accessKeySecret
  19. $endpoint = Yii::$app->params['aliyunoss']['endPoint']; //获取阿里云oss的endPoint
  20. self::$oss = new OssClient($accessKeyId, $accessKeySecret, $endpoint); //实例化OssClient对象
  21. }
  22. /**
  23. * 使用阿里云oss上传文件
  24. * @param $object 保存到阿里云oss的文件名
  25. * @param $filepath 文件在本地的绝对路径
  26. * @return bool 上传是否成功
  27. */
  28. public function upload($object, $filepath)
  29. {
  30. $res = false;
  31. $bucket = Yii::$app->params['aliyunoss']['bucket']; //获取阿里云oss的bucket
  32. if (self::$oss->uploadFile($bucket, $object, $filepath)) { //调用uploadFile方法把服务器文件上传到阿里云oss
  33. $res = true;
  34. }
  35. return $res;
  36. }
  37. /**
  38. * 删除指定文件
  39. * @param $object 被删除的文件名
  40. * @return bool 删除是否成功
  41. */
  42. public function delete($object)
  43. {
  44. $res = false;
  45. $bucket = Yii::$app->params['oss']['bucket']; //获取阿里云oss的bucket
  46. if (self::$oss->deleteObject($bucket, $object)){ //调用deleteObject方法把服务器文件上传到阿里云oss
  47. $res = true;
  48. }
  49. return $res;
  50. }
  51. public function test(){
  52. echo 123;
  53. echo "success";
  54. }
  55. }