Yii2.0 uses Alibaba Cloud OSS SDK to upload, download, and delete images.

不言
Release: 2023-03-25 16:52:02
Original
2426 people have browsed it

本篇文章主要介绍了Yii2.0使用阿里云OSS的SDK上传图片、下载、删除图片示例,具有一定的参考价值,有兴趣的可以了解一下

之前从没接触过Yii,借助的各方资源来做的这个整合阿里云OSS的SDK上传图片实例,如果有不正之处请指出!
前面参照了weinirumo 的介绍,大家可以自行去查看。

好了,下面开始进入主题:

准备工作:需要使用composer执行命令,如果没有安装composer的需要提前安装,参考文档:composer安装流程

1、项目目录结构

我使用的是基础版,只有后台目录,请自行对照自己的项目目录结构,会用到以下的几个目录:

2、在项目根目录下运行cmd命令


3、执行composer命令

切换到中国国内镜像

复制代码 代码如下:

composer  config -g repo.packagist composer https://packagist.phpcomposer.com
Copy after login

执行加载SDK命令

composer require aliyuncs/oss-sdk-php
Copy after login

4、查看根目录/vendor/里面,会增加以下目录文件,说明安装依赖文件成功:

5、在根目录/common/里面新建components目录,新建Aliyunoss.php文件

需要注意项目的命名空间,引入文件

6、根目录/common/components/Aliyunoss.php代码:

<?php
/**
 * @Author: Marte
 * @Date:  2017-09-04 11:31:20
 * @Last Modified by:  Marte
 * @Last Modified time: 2017-09-06 16:19:28
 */
namespace common\components;

use Yii;
use yii\base\Component;
use OSS\OssClient;
use OSS\Croe\OssException;

class Aliyunoss extends Component
{
  public static $oss;

  public function __construct()
  {
    parent::__construct();
    $accessKeyId = Yii::$app->params[&#39;oss&#39;][&#39;accessKeyId&#39;];         //获取阿里云oss的accessKeyId
    $accessKeySecret = Yii::$app->params[&#39;oss&#39;][&#39;accessKeySecret&#39;];     //获取阿里云oss的accessKeySecret
    $endpoint = Yii::$app->params[&#39;oss&#39;][&#39;endPoint&#39;];            //获取阿里云oss的endPoint
    self::$oss = new OssClient($accessKeyId, $accessKeySecret, $endpoint); //实例化OssClient对象
  }

  /**
   * 使用阿里云oss上传文件
   * @param $object  保存到阿里云oss的文件名
   * @param $filepath 文件在本地的绝对路径
   * @return bool   上传是否成功
   */
  public function upload($object, $filepath)
  {
    // $res = false;
    $bucket = Yii::$app->params[&#39;oss&#39;][&#39;bucket&#39;]; //获取阿里云oss的bucket

    $result=array();
    try{
      $getOssInfo=self::$oss->uploadFile($bucket, $object, $filepath);
      $result[&#39;url&#39;] = $getOssInfo[&#39;info&#39;][&#39;url&#39;];
      if($getOssInfo[&#39;info&#39;][&#39;url&#39;]){
        @unlink(substr($_path, 1));
      }
    }catch(OssException $e){
      var_dump($e);
      return;
    };
    $url=$result[&#39;url&#39;];
    return $url;
    // var_dump("$url");die();

   //   $res = true;
    //   return $url;
  }


  /**
   * 删除指定文件
   * @param $object 被删除的文件名
   * @return bool  删除是否成功
   */
  public function delete($object)
  {
    $res = false;
    $bucket = Yii::$app->params[&#39;oss&#39;][&#39;bucket&#39;];  //获取阿里云oss的bucket
    if (self::$oss->deleteObject($bucket, $object)){
    //调用deleteObject方法把服务器文件上传到阿里云oss
      $res = true;
    }
    return $res;
  }

//测试
  public function test(){
    echo 123;
    echo "success";
  }
}
Copy after login

7、在根目录/common/config/main.php,添加:

  &#39;Aliyunoss&#39; => [
    &#39;class&#39; => &#39;common\components\Aliyunoss&#39;,
   ],
Copy after login


8、在根目录/common/config/params.php,添加sdk信息,代码需要自行修改

&#39;oss&#39; =>[                     //阿里云OSS
    &#39;ossServer&#39; => &#39;oss-cn-   .aliyuncs.com&#39;, //服务器外网地址,
    &#39;ossServerInternal&#39; => &#39;oss-cn-   .aliyuncs.com&#39;, //服务器内网地址
    &#39;accessKeyId&#39;=>&#39;    &#39;,
    &#39;accessKeySecret&#39;=>&#39;     &#39;,
    &#39;bucket&#39; => &#39;    &#39;,
    &#39;endPoint&#39; => &#39;     &#39;,
  ],
Copy after login

9、根目录/backend/controllers/控制器名.php,里面引用文件

//阿里云OSS执行
use common\components\Aliyunoss;
Copy after login

由于上传图片限制,自此至下面就看代码了

10、准备上传图片数据,

 public function actionAdd(){
    $img_banner = trim($_FILES[&#39;vend_banner&#39;][&#39;name&#39;]);
    $img_banner = explode(&#39;.&#39;,$img_banner);
    $imgs_banner = $img_banner[1];
    $img_banner = date(&#39;YmdHis&#39;).mt_rand(100,1000).md5($img_banner[0]);
    //文件重命名
    $vend_banners = "./images/upload/".$img_banner.&#39;.&#39;.$imgs_banner; 
    $vend_banner = $img_banner.&#39;.&#39;.$imgs_banner; 
   
    $uploadPath = dirname(dirname(__FILE__)).&#39;/web/images/upload/&#39;; // 取得临时文件路径
      if (!file_exists($uploadPath)) {
        @mkdir($uploadPath, 0777, true);
      }
    $file_Path_vend_banner = $uploadPath.$vend_banner;
    $filepath_vend_banner=str_replace("\\", "/",$file_Path_vend_banner);//绝对路径,上传第二个参数
    $object_vend_banner="data/Company/".$vend_banner;      //拼接存储路径和文件名称,上传第一个参数
    if(is_uploaded_file($_FILES[&#39;vend_banner&#39;][&#39;tmp_name&#39;])){ //判断是否post上传
      if(!move_uploaded_file($_FILES[&#39;vend_banner&#39;][&#39;tmp_name&#39;],$vend_banners)){
        //移动到临时目录里
        echo &#39;banner上传失败&#39;;exit();
      }
    }
    $vend_banner_url = Yii::$app->Aliyunoss->upload($object_vend_banner,$filepath_vend_banner);
     //调用新建的文件,执行OSS上传,返回的是上传到阿里云的OSS文件路径,打印出来是:
    //string(116) "http:// ******.oss-cn-******.aliyuncs.com/data/Company/20170908124236303cc17c30cd111c7215fc8f51f8790e0e1.jpg"
Copy after login

11、删除图片

$oss_url=$data2[0][&#39;vend_banner&#39;];//只要(上传时候的)图片名,
$object="data/Company/".$oss_url; //将你阿里云的存储路径+图片名=组成数据
$is_del = Yii::$app->Aliyunoss->delete($object);//删除指定的图片,返回true,否则返回false
Copy after login

相关推荐:

thinkPHP简单导入和使用阿里云OSSsdk的方法

The above is the detailed content of Yii2.0 uses Alibaba Cloud OSS SDK to upload, download, and delete images.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!