使用 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 !!

猜你喜欢

转载自blog.csdn.net/jartins/article/details/85166340