search
HomeBackend DevelopmentPHP TutorialExample of uploading a single file to yii2.0 oss

Example of uploading a single file to yii2.0 oss

Sep 21, 2017 am 10:10 AM
documentExample

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() ?>

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]);
  }

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);
  }
}

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 Example of uploading a single file to yii2.0 oss. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.