1. 程式人生 > >使用 thinkphp5 + 阿里雲oss

使用 thinkphp5 + 阿里雲oss

第一步:執行composer

composer require aliyuncs/oss-sdk-php

     執行完畢可在vender下看到元件

 

第二步:預先準備的     $accessKeyId, $accessKeySecret, $endpoint,$bucket.

 

第三步:在 application/index/controller/Common.php 建立Common.php  存阿里雲oss的公共方法

<?php
namespace app\index\controller;

use think\Controller;
use think\Config;
use OSS\OssClient;
use OSS\Core\OssException;
class common extends Controller
{
    Public function moveOss($accessKeyId,$accessKeySecret,$endpoint,$bucket,$object,$content)
    {
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $res= $ossClient->putObject($bucket, $object, $content);
        } catch (OssException $e) {
            print $e->getMessage();
        }
        return $res['info']['url'];
    }
}

 

第四步:在 application/index/controller/Index.php 建立Index.php  繼承以上的 Common

<?php
namespace app\index\controller;

use think\Controller;
use think\File;
class Index extends common
{
    public function index()
    {
        error_reporting(0);
        header("Content-type:text/html;charset=utf-8");
        if($this->request->isPost()){
            $arrList1= $_FILES['image']['name'];
            $arrList2= $_FILES['image']['tmp_name'];
            $info2=array();
            for($i=0;$i<count($arrList1);$i++){
                $object= $arrList1[$i];
                $content=file_get_contents($arrList2[$i]);
                $info=$this->moveOss('AccessKey ID','Access Key Secret',
                    'EndPoint(地域節點)','Bucket域名',$object,$content);
                $arr2[]=$info;
              //echo $info;echo "<br/>";
            }
           $result=implode(';',$arr2);
           print_r($result);

        }else{
            return view();
        }

    }
  
}

 

第五步:檢視demo 一個 view/index/index.html 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>阿里雲oss檔案上傳</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" name="fileinfo" action="{:url('index/index')}">
    <table>
        <tr>
            <td>上傳檔案:</td>
            <td><input type="file" name="image[]" multiple="multiple"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="上傳" ></td>
        </tr>
    </table>
</form>
</body>
</html>

 

 

 

------- complate !!