Home > Backend Development > PHP Tutorial > How to integrate Alibaba Cloud oss ​​with yii2.0 to upload a single file

How to integrate Alibaba Cloud oss ​​with yii2.0 to upload a single file

黄舟
Release: 2023-03-16 09:38:02
Original
1613 people have browsed it

This article mainly introduces the example of Yii2.0 integrating Alibaba Cloud oss ​​to upload a single file. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

The previous article has introduced how to integrate Alibaba Cloud oss. This article mainly introduces uploading files to Alibaba Cloud oss.

Main idea: First, the files must be uploaded to the server, and then the files in the server should be transferred to Alibaba Cloud oss. After success, the file information will be written to the database. If it fails, the server files will be deleted.

Main steps:

0 Introduce several oss concepts.

accessKeyId ==>> It can be understood as the account number for accessing Alibaba Cloud OSS

accessKeySecret ==>> It can be understood as the password for accessing Alibaba Cloud OSS

bucket ==>> It can be understood as the root directory where the file is saved

endPoint ==>> Put it between the space and ossfile to form the url path for accessing the file, and also to obtain Ali Cloud pictures way.

object ==>> After your file is transferred to Alibaba Cloud oss, what is the path and what is its name?

It is easier to understand by looking at the screenshot:

1 File uploading still involves mvc. This time we start from the view, which mainly displays a form for submitting files. The aliyunoss.php code is as follows:


<?php
use yii\widgets\ActiveForm;
?>

<?php $form = ActiveForm::begin([&#39;options&#39; => [&#39;enctype&#39; => &#39;multipart/form-data&#39;]]) ?>

<?= $form->field($model, &#39;files&#39;)->fileInput() ?>

  <button>Submit</button>

<?php ActiveForm::end() ?>
Copy after login

2 Receive the file in the controller and transfer it to the model for processing. The sample code of UploadController is as follows:


public function actionTestAliyun()
  {
    $model = new UploadForm(); // 实例化上传类
    if (Yii::$app->request->isPost) {
      $model->files = UploadedFile::getInstance($model,&#39;files&#39;); //使用UploadedFile的getInstance方法接收单个文件

      $model->setScenario(&#39;upload&#39;); // 设置upload场景
      $res = $model->uploadfile(); //调用model里边的upload方法执行上传
      $err = $model->getErrors(); //获取错误信息

      echo "<pre class="brush:php;toolbar:false">";
      print_r($res); //打印上传结果
      print_r($err); //打印错误信息,方便排错
      exit;

    }

    return $this->render(&#39;aliyunoss&#39;,[&#39;model&#39;=>$model]);
  }
Copy after login

3 When the controller transfers the image to the model file UploadForm.php, it must first move the file to the upload directory of the server, and then Move to Alibaba Cloud. The code is as follows:


<?php
/**
 * Created by PhpStorm.
 * Description: 阿里oss上传图片
 * Author: Weini
 * Date: 2016/11/17 0017
 * Time: 上午 11:34
 */

namespace app\models;

use Yii;
use yii\base\Exception;
use yii\base\Model;

class UploadForm extends Model
{
  public $files; //用来保存文件

  public function scenarios()
  {
    return [
      &#39;upload&#39; => [&#39;files&#39;], // 添加上传场景
    ];
  }

  public function rules(){
    return [
      [[&#39;files&#39;],&#39;file&#39;, &#39;skipOnEmpty&#39; => false, &#39;extensions&#39; => &#39;jpg, png, gif&#39;, &#39;mimeTypes&#39;=>&#39;image/jpeg, image/png, image/gif&#39;, &#39;maxSize&#39;=>1024*1024*10, &#39;maxFiles&#39;=>1, &#39;on&#39;=>[&#39;upload&#39;]],
      //设置图片的验证规则
    ];
  }

  /**
   * 上传单个文件到阿里云
   * @return boolean 上传是否成功
   */
  public function uploadfile(){
    $res[&#39;error&#39;] = 1;

    if ($this->validate()) {
      $uploadPath = dirname(dirname(__FILE__)).&#39;/web/uploads/&#39;; // 取得上传路径
      if (!file_exists($uploadPath)) {
        @mkdir($uploadPath, 0777, true);
      }

      $ext = $this->files->getExtension();        // 获取文件的扩展名
      $randnums = $this->getrandnums();          // 生成一个随机数,为了重命名文件
      $imageName = date("YmdHis").$randnums.&#39;.&#39;.$ext;   // 重命名文件
      $ossfile = &#39;file/&#39;.date("Ymd").&#39;/&#39;.$imageName;   // 这里是保存到阿里云oss的文件名和路径。如果只有文件名,就会放到空间的根目录下。
      $filePath = $uploadPath.$imageName;         // 生成文件的绝对路径

      if ($this->files->saveAs($filePath)){        // 上传文件到服务器
        $filedata[&#39;filename&#39;] = $imageName;       // 准备图片信息,保存到数据库
        $filedata[&#39;filePath&#39;] = $filePath;       // 准备图片信息,保存到数据库
        $filedata[&#39;ossfile&#39;] = $ossfile;        // 准备图片信息,保存到数据库
        $filedata[&#39;userid&#39;] = Yii::$app->user->id;   // 准备图片信息,保存到数据库,这个字段必须要,以免其他用户恶意删除别人的图片
        $filedata[&#39;uploadtime&#39;] = time();        // 准备图片信息,保存到数据库

        // 上边这些代码不能照搬,要根据你项目的需求进行相应的修改。反正目的就是记录上传文件的信息
        // 老板,这些代码是我搬来的,没仔细看,如果出问题了,你就扣我的奖金吧^_^

        $trans = Yii::$app->db->beginTransaction();   // 开启事务
        try{
          $savefile = Yii::$app->db->createCommand()->insert(&#39;file&#39;, $filedata)->execute(); //把文件的上传信息写入数据库
          $newid = Yii::$app->db->getLastInsertID(); //获取新增文件的id,用于返回。

          if ($savefile) {              // 如果插入数据库成功
            $ossupload = Yii::$app->Aliyunoss->upload($ossfile, $filePath); //调用Aliyunoss组件里边的upload方法把文件上传到阿里云oss

            if ($ossupload) {            // 如果上传成功,
              $res[&#39;error&#39;] = 0;         // 准备返回信息
              $res[&#39;fileid&#39;] = $newid;      // 准备返回信息
              $res[&#39;ossfile&#39;] = $ossfile;     // 准备返回信息
              $trans->commit();          // 提交事务
            } else {                // 如果上传失败
              unlink($filePath);         // 删除服务器上的文件
              $trans->rollBack();         // 事务回滚
            }
          }
          unlink($filePath);             // 插入数据库失败,删除服务器上的文件
          $trans->rollBack();             // 事务回滚
        } catch(Exception $e) {             // 出了异常
          unlink($filePath);             // 删除服务器上的文件
          $trans->rollBack();             // 事务回滚
        }

      }
    }

    return $res;                      // 返回上传信息
  }

  /**
   * 生成随机数
   * @return string 随机数
   */
  protected function getrandnums()
  {
    $arr = array();
    while (count($arr) < 10) {
      $arr[] = rand(1, 10);
      $arr = array_unique($arr);
    }
    return implode("", $arr);
  }
}
Copy after login

If you encounter an error saying that no files are uploaded, it is most likely because the image verification rule setting maxFiles is greater than 1. Just change it to 1.

Please note that the above code will report a curl connection timeout error in the local test environment, but there is no problem when running on the server.

The above is the detailed content of How to integrate Alibaba Cloud oss ​​with yii2.0 to upload a single file. 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