整合百度UEditor上傳圖片到阿里雲OSS

前言

將圖片上傳到阿里雲OSS是一種趨勢,一個必然。當你的項目圖片過多,須要頻繁上傳和替換的時候,用阿里雲OSS能夠很方便的管理你的圖片,節省服務器空間,大大提升了效率。阿里雲OSS是阿里雲提供的海量、安全、低成本、高可靠的雲存儲服務。你能夠經過調用API,在任何應用、任什麼時候間、任何地點上傳和下載數據,也能夠經過Web控制檯對數據進行簡單的管理。阿里雲OSS適合存聽任意類型的文件,適合各類網站、開發企業及開發者使用。php

若是直接把圖片上傳到阿里雲OSS是比較簡單的,應該不少人都懂,可是用百度UEditor上傳圖片到阿里雲OSS,就沒那麼簡單了,因此我感受仍是有必要寫這篇文章分享出來,給有須要的人。html

效果圖

圖片描述

修改百度UEditor的文件

一、修改這幾個文件:圖片描述git

1.一、修改Uploader.class.php文件github

注意:修改的部分我有加註釋,注意看。web

<?php


/**
 * Created by JetBrains PhpStorm.
 * User: taoqili
 * Date: 12-7-18
 * Time: 上午11: 32
 * UEditor編輯器通用上傳類
 */
class Uploader
{

    private $fileField; //文件域名
    private $file; //文件上傳對象
    private $base64; //文件上傳對象
    private $config; //配置信息
    private $oriName; //原始文件名
    private $fileName; //新文件名
    private $fullName; //完整文件名,即從當前配置目錄開始的URL
    private $filePath; //完整文件名,即從當前配置目錄開始的URL
    private $fileSize; //文件大小
    private $fileType; //文件類型
    private $stateInfo; //上傳狀態信息,
    private $stateMap = array( //上傳狀態映射表,國際化用戶需考慮此處數據的國際化
        "SUCCESS", //上傳成功標記,在UEditor中內不可改變,不然flash判斷會出錯
        "文件大小超出 upload_max_filesize 限制",
        "文件大小超出 MAX_FILE_SIZE 限制",
        "文件未被完整上傳",
        "沒有文件被上傳",
        "上傳文件爲空",
        "ERROR_TMP_FILE" => "臨時文件錯誤",
        "ERROR_TMP_FILE_NOT_FOUND" => "找不到臨時文件",
        "ERROR_SIZE_EXCEED" => "文件大小超出網站限制",
        "ERROR_TYPE_NOT_ALLOWED" => "文件類型不容許",
        "ERROR_CREATE_DIR" => "目錄建立失敗",
        "ERROR_DIR_NOT_WRITEABLE" => "目錄沒有寫權限",
        "ERROR_FILE_MOVE" => "文件保存時出錯",
        "ERROR_FILE_NOT_FOUND" => "找不到上傳文件",
        "ERROR_WRITE_CONTENT" => "寫入文件內容錯誤",
        "ERROR_UNKNOWN" => "未知錯誤",
        "ERROR_DEAD_LINK" => "連接不可用",
        "ERROR_HTTP_LINK" => "連接不是http連接",
        "ERROR_HTTP_CONTENTTYPE" => "連接contentType不正確"
    );

    /**
     * 構造函數
     * @param string $fileField 表單名稱
     * @param array $config 配置項
     * @param bool $base64 是否解析base64編碼,可省略。若開啓,則$fileField表明的是base64編碼的字符串表單名
     */
    public function __construct($fileField, $config, $type = "upload")
    {
        $this->fileField = $fileField;
        $this->config = $config;
        $this->type = $type;
        if ($type == "remote") {
            $this->saveRemote();
        } else if($type == "base64") {
            $this->upBase64();
        } else {
            $this->upFile();
        }

        $this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
    }

    /**
     * 上傳文件的主處理方法
     * @return mixed
     */
    private function upFile()
    {  
        $file = $this->file = $_FILES[$this->fileField];  
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }
        
        //修改:上傳阿里雲OSS
        $upload=new \source\core\widgets\upload\FileUpload();
        
        $Pictureinfo=$upload->UploadUeditorPicture($file);

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();
        $this->fullName = '/'.$Pictureinfo['path'];
        $this->filePath = $Pictureinfo['path'];
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //檢查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //檢查是否不容許的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //建立目錄失敗
        // if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
        //     $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
        //     return;
        // } else if (!is_writeable($dirname)) {
        //     $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
        //     return;
        // }

        $this->stateInfo = $this->stateMap[0];
        //移動文件
        // if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移動失敗

        //     $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        // } else { //移動成功
        //     $this->stateInfo = $this->stateMap[0];
        // }

    }

    /**
     * 處理base64編碼的圖片上傳
     * @return mixed
     */
    private function upBase64()
    {
        $base64Data = $_POST[$this->fileField];
        $img = base64_decode($base64Data);

        $this->oriName = $this->config['oriName'];
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //檢查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //建立目錄失敗
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移動文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移動失敗
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移動成功
            $this->stateInfo = $this->stateMap[0];
        }

    }

    /**
     * 拉取遠程圖片
     * @return mixed
     */
    private function saveRemote()
    {
        $imgUrl = htmlspecialchars($this->fileField);
        $imgUrl = str_replace("&amp;", "&", $imgUrl);

        //http開頭驗證
        if (strpos($imgUrl, "http") !== 0) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
            return;
        }
        //獲取請求頭並檢測死鏈
        $heads = get_headers($imgUrl);
        if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
            $this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
            return;
        }
        //格式驗證(擴展名驗證和Content-Type驗證)
        $fileType = strtolower(strrchr($imgUrl, '.'));
        if (!in_array($fileType, $this->config['allowFiles']) || stristr($heads['Content-Type'], "image")) {
            $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
            return;
        }

        //打開輸出緩衝區並獲取遠程圖片
        ob_start();
        $context = stream_context_create(
            array('http' => array(
                'follow_location' => false // don't follow redirects
            ))
        );
        readfile($imgUrl, false, $context);

        $img = ob_get_contents();
        ob_end_clean();
        preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);

        $this->oriName = $m ? $m[1]:"";
        $this->fileSize = strlen($img);
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //檢查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //建立目錄失敗
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移動文件
        if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移動失敗
            $this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
        } else { //移動成功
            $this->stateInfo = $this->stateMap[0];
        }

    }

    /**
     * 上傳錯誤檢查
     * @param $errCode
     * @return string
     */
    private function getStateInfo($errCode)
    {
        return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
    }

    /**
     * 獲取文件擴展名
     * @return string
     */
    private function getFileExt()
    {
        return strtolower(strrchr($this->oriName, '.'));
    }

    /**
     * 重命名文件
     * @return string
     */
    private function getFullName()
    {
        //替換日期事件
        $t = time();
        $d = explode('-', date("Y-y-m-d-H-i-s"));
        $format = $this->config["pathFormat"];
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);

        //過濾文件名的非法自負,並替換文件名
        $oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
        $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
        $format = str_replace("{filename}", $oriName, $format);

        //替換隨機字符串
        $randNum = rand(1, 10000000000) . rand(1, 10000000000);
        if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
            $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
        }

        $ext = $this->getFileExt();
        return $format . $ext;
    }

    /**
     * 獲取文件名
     * @return string
     */
    private function getFileName () {
        return substr($this->filePath, strrpos($this->filePath, '/') + 1);
    }

    /**
     * 獲取文件完整路徑
     * @return string
     */
    private function getFilePath()
    {
        $fullname = $this->fullName;
        
        // $rootPath = $_SERVER['DOCUMENT_ROOT'];

        // if (substr($fullname, 0, 1) != '/') {
        //     $fullname = '/' . $fullname;
        // }

        //修改:替換路徑
        return  $fullname;
    }

    /**
     * 文件類型檢測
     * @return bool
     */
    private function checkType()
    {
        return in_array($this->getFileExt(), $this->config["allowFiles"]);
    }

    /**
     * 文件大小檢測
     * @return bool
     */
    private function  checkSize()
    {
        return $this->fileSize <= ($this->config["maxSize"]);
    }

    /**
     * 獲取當前上傳成功文件的各項信息
     * @return array
     */
    public function getFileInfo()
    { 
        return array(
            "state" => $this->stateInfo,
            "url" => $this->fullName,
            "title" => $this->fileName,
            "original" => $this->oriName,
            "type" => $this->fileType,
            "size" => $this->fileSize
        );
    }

}

1.二、修改config.json文件,這個文件主要是修改圖片路徑,改成你的阿里雲OSS的路徑數據庫

/* 先後端通訊相關的配置,註釋只容許使用多行方式 */
{
    /* 上傳圖片配置項 */
    "imageActionName": "uploadimage", /* 執行上傳圖片的action名稱 */
    "imageFieldName": "upfile", /* 提交的圖片表單名稱 */
    "imageMaxSize": 2048000, /* 上傳大小限制,單位B */
    "imageAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 上傳圖片格式顯示 */
    "imageCompressEnable": true, /* 是否壓縮圖片,默認是true */
    "imageCompressBorder": 1600, /* 圖片壓縮最長邊限制 */
    "imageInsertAlign": "none", /* 插入的圖片浮動方式 */
    "imageUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 圖片訪問路徑前綴 */
    "imagePathFormat": "data/attachment/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
                                /* {filename} 會替換成原文件名,配置這項須要注意中文亂碼問題 */
                                /* {rand:6} 會替換成隨機數,後面的數字是隨機數的位數 */
                                /* {time} 會替換成時間戳 */
                                /* {yyyy} 會替換成四位年份 */
                                /* {yy} 會替換成兩位年份 */
                                /* {mm} 會替換成兩位月份 */
                                /* {dd} 會替換成兩位日期 */
                                /* {hh} 會替換成兩位小時 */
                                /* {ii} 會替換成兩位分鐘 */
                                /* {ss} 會替換成兩位秒 */
                                /* 非法字符 \ : * ? " < > | */
                                /* 具請體看線上文檔: fex.baidu.com/ueditor/#use-format_upload_filename */

    /* 塗鴉圖片上傳配置項 */
    "scrawlActionName": "uploadscrawl", /* 執行上傳塗鴉的action名稱 */
    "scrawlFieldName": "upfile", /* 提交的圖片表單名稱 */
    "scrawlPathFormat": "data/attachment/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "scrawlMaxSize": 2048000, /* 上傳大小限制,單位B */
    "scrawlUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 圖片訪問路徑前綴 */
    "scrawlInsertAlign": "none",

    /* 截圖工具上傳 */
    "snapscreenActionName": "uploadimage", /* 執行上傳截圖的action名稱 */
    "snapscreenPathFormat": "/data/attachment/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "snapscreenUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 圖片訪問路徑前綴 */
    "snapscreenInsertAlign": "none", /* 插入的圖片浮動方式 */

    /* 抓取遠程圖片配置 */
    "catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
    "catcherActionName": "catchimage", /* 執行抓取遠程圖片的action名稱 */
    "catcherFieldName": "source", /* 提交的圖片列表表單名稱 */
    "catcherPathFormat": "/data/attachment/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "catcherUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 圖片訪問路徑前綴 */
    "catcherMaxSize": 2048000, /* 上傳大小限制,單位B */
    "catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取圖片格式顯示 */

    /* 上傳視頻配置 */
    "videoActionName": "uploadvideo", /* 執行上傳視頻的action名稱 */
    "videoFieldName": "upfile", /* 提交的視頻表單名稱 */
    "videoPathFormat": "/data/attachment/video/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "videoUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 視頻訪問路徑前綴 */
    "videoMaxSize": 102400000, /* 上傳大小限制,單位B,默認100MB */
    "videoAllowFiles": [
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上傳視頻格式顯示 */

    /* 上傳文件配置 */
    "fileActionName": "uploadfile", /* controller裏,執行上傳視頻的action名稱 */
    "fileFieldName": "upfile", /* 提交的文件表單名稱 */
    "filePathFormat": "/data/attachment/file/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳保存路徑,能夠自定義保存路徑和文件名格式 */
    "fileUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 文件訪問路徑前綴 */
    "fileMaxSize": 51200000, /* 上傳大小限制,單位B,默認50MB */
    "fileAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ], /* 上傳文件格式顯示 */

    /* 列出指定目錄下的圖片 */
    "imageManagerActionName": "listimage", /* 執行圖片管理的action名稱 */
    "imageManagerListPath": "/data/attachment/image/", /* 指定要列出圖片的目錄 */
    "imageManagerListSize": 20, /* 每次列出文件數量 */
    "imageManagerUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 圖片訪問路徑前綴 */
    "imageManagerInsertAlign": "none", /* 插入的圖片浮動方式 */
    "imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件類型 */

    /* 列出指定目錄下的文件 */
    "fileManagerActionName": "listfile", /* 執行文件管理的action名稱 */
    "fileManagerListPath": "/data/attachment/file/", /* 指定要列出文件的目錄 */
    "fileManagerUrlPrefix": "http://test.oss-cn-hangzhou.aliyuncs.com", /* 文件訪問路徑前綴 */
    "fileManagerListSize": 20, /* 每次列出文件數量 */
    "fileManagerAllowFiles": [
        ".png", ".jpg", ".jpeg", ".gif", ".bmp",
        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"
    ] /* 列出的文件類型 */

}

1.三、action_upload.php、action_list.php、action_crawler.php這三個文件主要是引用上傳到阿里雲OSS的文件FileUpload.php,都加入以下代碼便可json

include (__DIR__."/../../../../../../source/core/widgets/upload/FileUpload.php");

FileUpload.php文件上傳到阿里雲OSS的代碼

<?php
namespace source\core\widgets\upload;

use Yii;
use yii\base\Action;
use yii\base\ActionFilter;
use source\models\Upload;
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
use source\core\widgets\encrypt\AesMask;
use source\models\User;

class FileUpload 
{
    const endpoint = "填寫你的endpoint";
    const accessKeyId = "填寫你的accessKeyId";
    const accessKeySecret = "填寫你的accessKeyId";


  //百度編輯器圖片上傳
  public static function UploadUeditorPicture($file)
  {  
        include (__DIR__."/../../../../vendor/aliyuncs/oss-sdk-php/src/OSS/OssClient.php");  
        include (__DIR__."/../../../../vendor/aliyuncs/oss-sdk-php/src/OSS/Core/OssException.php");      
        include (__DIR__."/../../../../vendor/aliyuncs/oss-sdk-php/src/OSS/Core/OssUtil.php");
        include (__DIR__."/../../../../vendor/aliyuncs/oss-sdk-php/src/OSS/Core/MimeTypes.php");
        include (__DIR__."/../../../../vendor/aliyuncs/oss-sdk-php/src/OSS/Http/RequestCore.php");
        include (__DIR__."/../../../../vendor/aliyuncs/oss-sdk-php/src/OSS/Http/ResponseCore.php");
        include (__DIR__."/../../../../vendor/aliyuncs/oss-sdk-php/src/OSS/Result/Result.php");
        include (__DIR__."/../../../../vendor/aliyuncs/oss-sdk-php/src/OSS/Result/PutSetDeleteResult.php");

        include ("/../encrypt/StrMask.php");
        include ("/../encrypt/AesMask.php");

        $ossClient = new \OSS\OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint);

        $data = ['id'=>1,'modules_name'=>'ueditor','user_id'=>1];
        $model = array();
        $bucket = 'test';
        if(empty($data['id'])){
             $model['status']="ID不能爲空";
             return $model; 
        }
        if(!isset($data['modules_name'])){
             $model['status']="模塊名稱不能爲空";
             return $model; 
        }
        if(!isset($data['user_id'])){
             $model['status']="用戶id不能爲空";
             return $model; 
        }
        $path = self::Encrypt($data['modules_name'],$data['id'],$data['user_id']);//對上傳的路徑加密

        if(!empty($file)){

            $randName = time() . rand(1000, 9999) . strtolower(strrchr($file['name'], '.'));
            $name = $path.$randName;
            $tempName=!empty($file['tmp_name'])?$file['tmp_name']:"";

            $ossClient->uploadFile($bucket,$name,$tempName);

            return  ['path'=>$name,'randName'=>$randName];
        } 

        return ['path'=>'','randName'=>''];   
       
  }
  
  
    /**
   * 刪除附件
   *
   * @param  path      string  y upload表返回的附件上傳路徑path 字段\n
   * @return status   string    結果信息
   */
 static public function DownloadDelete($path)
 {
       $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint);
       $bucket = "test";
       if(!isset($path)){
            $model['status']="附件路徑不能爲空";
            return $model;
       }
       $ossClient->deleteObject($bucket, $path);
       $model['status']="刪除成功";
       return $model;
      
  }
  
  
   /**
   * 批量刪除附件
   *
   * @param  path      string  y upload表返回的附件上傳路徑path 字段\n
   * @return status   string    結果信息
   */
 static public function DownloadDeletes($data)
 {
       $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint);
       $bucket = "test";
       if(!isset($data)){
            $model['status']="刪除數組不能爲空";
            return $model;
       }
       $ossClient->deleteObjects($bucket, $data); 
       $model['status']="刪除成功";
       return $model;
      
  }

  function getObject($object)
  {
        $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint);
        $options = array();
        $bucket = "test";
        
        $timeout = 3600;
        $options = NULL;
        try {
            $signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT");
        } catch (OssException $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return;
        }
        print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
        $content = file_get_contents(__FILE__);

        $request = new RequestCore($signedUrl);
        $request->set_method('PUT');
        $request->add_header('Content-Type', '');
        $request->add_header('Content-Length', strlen($content));
        $request->set_body($content);
        $request->send_request();
        $res = new ResponseCore($request->get_response_header(),
            $request->get_response_body(), $request->get_response_code());
        if ($res->isOK()) {
            print(__FUNCTION__ . ": OK" . "\n");
        } else {
            print(__FUNCTION__ . ": FAILED" . "\n");
        };
    }
  
  
   /**
   * 加密路徑
   *
   * @param array $data       Y 參數數組(array('modules_name'=>$modules_name,'bucket'=>'test','path'=>'upload/accessory/14585506176746.jpg'))\n
   * --modules_name   string  Y 模塊名稱\n
   * --id             string  Y id\n
   * @return status   string    結果信息
   */
 static public function Encrypt($modules_name,$id,$user_id='')
 {

       if(empty($user_id)){
          $user_id =  Yii::$app->user->id;
       }
       
       $modules_path = AesMask::encrypt($modules_name,'test');
       
       $id_path = AesMask::encrypt($id,'test');
       
       return "test/".$modules_path."/".$id_path."/";
  }
  
}
?>

新增圖片Controller的代碼

public function actionCreate()
{  
        $username=!empty(Yii::$app->user->identity->attributes['username'])?Yii::$app->user->identity->attributes['username']:"";
        $model = new Product();  
        $model->user_id=Yii::$app->user->id;
        $model->user_name = $username;
        $model->product_type=$this->product_type;
        $model->loadDefaultValues();
        
        $bodyModel = $this->getBodyModel();
        $bodyModel->loadDefaultValues();
        
        if(($r = $this->saveProduct($model, $bodyModel))!==false)
        {
            return $r;
        }
        
        //產品屬性
        $product_items=[];

        return $this->render('create', [
                'model' => $model,
                'bodyModel' => $bodyModel,
                'product_items'=>$product_items,
                ]);
}

 public function saveProduct($model, $bodyModel)
 { 
        $postDatas = Yii::$app->request->post();

        if ($model->load($postDatas) && $bodyModel->load($postDatas) && $model->validate() && $bodyModel->validate()) {
            
            if($model->summary===null|| $model->summary ==='')
            {
                if($bodyModel->hasAttribute('body'))
                {
                    $product = strip_tags($bodyModel->body);
                    $pattern = '/\s/';//去除空白
                    $product = preg_replace($pattern, '', $product);
                     
                    $model->summary=StringHelper::subStr($product,250);
                }
            }

            if($model->save())
            {  
                $bodyModel->product_id = $model->id; 
                $bodyModel->save();
                //保存百度編輯器的圖片
                $this->saveUpload($bodyModel->body,$model->id);
                //屬性
                if(!empty($postDatas['ProductItems'])){
                    ProductItems::deleteAll(['product_id'=>$model->id]);
                    foreach ($postDatas['ProductItems']['type'] as $key => $val) {
                        $modelItems = new ProductItems();
                        $modelItems->product_id = $model->id;
                        $modelItems->type = !empty($postDatas['ProductItems']['type'][$key])?$postDatas['ProductItems']['type'][$key]:"";
                        $modelItems->source = !empty($postDatas['ProductItems']['source'][$key])?$postDatas['ProductItems']['source'][$key]:"";
                        $modelItems->ticket_pat = !empty($postDatas['ProductItems']['ticket_pat'][$key])?$postDatas['ProductItems']['ticket_pat'][$key]:"";
                        $modelItems->ticket_pats = !empty($postDatas['ProductItems']['ticket_pats'][$key])?$postDatas['ProductItems']['ticket_pats'][$key]:"";
                        $modelItems->save();
                    }
                }

                return $this->redirect(['index']);
            }
        }
        return false;
}
 //保存圖片
public function saveUpload($body,$task_id)
{   
        $error['status']="內容爲空";
        if(!empty($body) && $task_id){ 
            $preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i'; //獲取百度編輯器裏提交的圖片路徑
            preg_match_all($preg, $body, $imgArr);
        
            if(!empty($imgArr[1])){
                foreach ($imgArr[1] as $key => $val) { 
                    $_imgArr = explode('/wpzx/', $val);  
                    $path='wpzx/'.$_imgArr[1];
                    $suffix = pathinfo($_imgArr[1]);  
                    $img_info = getimagesize($val);

                    $model= new Upload();
                    if($suffix['extension'] == 'jpg' || $suffix['extension'] == 'JPG'|| $suffix['extension'] == 'png'|| $suffix['extension'] == 'PNG'|| $suffix['extension'] == 'jpeg'){
                        $model->thumb        = $path;
                    }

                    $model->task_id          = $task_id;
                    $model->name             = $suffix['basename'];
                    $model->path             = $path;
                    $model->status           = 1;
                    $model->user_id          = Yii::$app->user->id;
                    $model->size             = $img_info[0]*$img_info[1];
                    $model->type             = $img_info['mime'];
                    $model->upload_time      = time();
                    $model->module_id        = 3;
                    $model->modules_name     = 'product';
                    $model->target           = 1;
                    
                    if (!$model->save()) {
                        $error['status']="失敗"; 
                    }
                }
                if($error['status']!="失敗"){
                    return true;
                }
                return $error;
            }
        }
        //刪除upload與阿里雲的圖片  
        $upload=Upload::getUploadsAll($task_id,'product'); 
        if(!empty($upload)){
            FileUpload::DownloadDeletes(ArrayHelper::getColumn($upload, 'path'));
            Upload::deleteAll(['task_id'=>$task_id,'modules_name'=>'product']);  
        }   
}

//根據指定條件獲取全部上傳圖片
 public static function getUploadsAll($task_id,$modules_name)
 {
        $data=[];
        $query=Upload::find()->where(['modules_name'=>$modules_name]);
        if(!empty($task_id)){
            $data=$query->andWhere(['task_id'=>$task_id])->all();
        }else{
            $data=$query->all();
        }
        
        return $data;
 }

//upload表的字段以下,僅供參考
 public function attributeLabels()
 {
        return [
            'id' => 'ID',
            'name' => '上傳文件名',
            'path' => '文件路徑',
            'status' => '上傳狀態',
            'task_id' => '所屬任務',
            'user_id' => '所屬用戶',
            'size' => '文件大小',
            'type' => '文件類型',
            'upload_time' => '上傳時間',
            'module_id' => '所屬系統',
            'thumb' => '縮略圖',
        ];
}

新增圖片Views的代碼

<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use source\models\Product;
use source\models\Takonomy;
use source\libs\Common;
use source\core\widgets\ueditor\Ueditor;

/* @var $this yii\web\View */
/* @var $model app\models\Product */
/* @var $form yii\widgets\ActiveForm */

$filedOptions = [
    'template' => "{label}{input}\n{error}", 
    'labelOptions' => [
        'class' => 'control-label'
    ]
]
;

$takonomies = Takonomy::getArrayTree('product');

$options = Common::buildTreeOptions($takonomies, $model->takonomy_id);

?>

<div class="product-form ">


    <?php
                
$form = ActiveForm::begin([
                    'options'=>[
                        'enctype'=>'multipart/form-data',
                        
                        ],
                    'fieldConfig' => [
                        'template' => "{label}<div class=\"col-md-8\">{input}</div>\n{error}", 
                        'labelOptions' => [
                            'class' => 'col-md-4 control-label no-padding-left no-padding-right align-left'
                        ]
                    ], 
                    
                ]);
                ?>
    
<div class="row">
        <div class="col-md-9">
            <?= $form->field($model, 'title',$filedOptions)->textInput(['maxlength' => 256,'placeholder'=>'請輸入標題'])?>

            <?= $form->field($model, 'url_alias',$filedOptions)->textInput(['maxlength' => 128,'placeholder'=>'Url 地址'])?>

            <hr class="hr">

            
            <?=$form->field($bodyModel, 'body',$filedOptions)->widget(Ueditor::className(),[
                'options'=>[
                    'focus'=>true,
                    'toolbars'=> [
                         ['fullscreen', 'source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline','removeformat','autotypeset', '|', 'forecolor', 'backcolor', 'selectall', 'cleardoc','|','fontfamily', 'fontsize', '|', 'justifyleft', 'justifycenter', '|', 'link', 'unlink','|', 'insertimage', 'emotion','attachment','|', 'preview', 'searchreplace']  
                    ],
                ],
                'attributes'=>[
                    'style'=>'height:80px'
                ]
            ])?>
            
            
        </div>

        <div class="col-md-3 form-horizontal" >
    
            
             <div  class="form-group">
                <?= Html::submitButton($model->isNewRecord ? '新建' : '編輯', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'])?>
            </div>

    </div>

</div>
<?php ActiveForm::end(); ?>

</div>

總結分析

一、要修改的地方仍是挺多的,百度UEditor上傳後獲取圖片路徑保存到數據庫處理起來也有點繁瑣,若是大家有更好的方法,能夠給我留言,我們一塊討論。bootstrap

二、以上我只是處理了圖片上傳到阿里雲OSS,若是你們須要把視頻,Mp3等等附件上傳到阿里雲OSS也是一樣的方法,惟一的區別就是在提交表單的時候要獲取到對應的視頻,Mp3等等附件路徑保存到數據庫得處理一下。後端

相關資料

PHP-SDK 下載安裝地址
ueditor 下載地址數組

相關文章
相關標籤/搜索