百度ueditor編輯器圖片、文件、視頻直接上傳到阿里云oss

最近開發(fā)的項目中要求要把圖片文件等都直接上傳到阿里云,不放在服務器上
1、修改uploader.class.php,修改的地方我標紅了(添加了一下注釋。。然后代碼模板背景色全變黑色了。。標紅的樣式全不見了,自己對比一下代碼哈)

由于ueditor是第三方的插件,里面的uploader.class.php并不是框架里的東西,所有使用命名空間直接引用是引用不到oss的類的,同時框架里的自帶函數(shù)也不能使用,只能用原生php函數(shù)

<?php

/**

  • Created by JetBrains PhpStorm.
  • User: taoqili
  • Date: 12-7-18
  • Time: 上午11: 32
  • UEditor編輯器通用上傳類
    */
    require_once '../../../../Yunwan/Core/Library/Vendor/OSS/autoload.php';//這是我下載的阿里云oss sdk的路徑,你們的自己參考一下
    use OSS\OssClient;
    use OSS\Core\OssException;

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; //上傳狀態(tài)信息,
private $stateMap = array( //上傳狀態(tài)映射表,國際化用戶需考慮此處數(shù)據(jù)的國際化
    "SUCCESS", //上傳成功標記,在UEditor中內(nèi)不可改變,否則flash判斷會出錯
    "文件大小超出 upload_max_filesize 限制",
    "文件大小超出 MAX_FILE_SIZE 限制",
    "文件未被完整上傳",
    "沒有文件被上傳",
    "上傳文件為空",
    "ERROR_TMP_FILE" => "臨時文件錯誤",
    "ERROR_TMP_FILE_NOT_FOUND" => "找不到臨時文件",
    "ERROR_SIZE_EXCEED" => "文件大小超出網(wǎng)站限制",
    "ERROR_TYPE_NOT_ALLOWED" => "文件類型不允許",
    "ERROR_CREATE_DIR" => "目錄創(chuàng)建失敗",
    "ERROR_DIR_NOT_WRITEABLE" => "目錄沒有寫權(quán)限",
    "ERROR_FILE_MOVE" => "文件保存時出錯",
    "ERROR_FILE_NOT_FOUND" => "找不到上傳文件",
    "ERROR_WRITE_CONTENT" => "寫入文件內(nèi)容錯誤",
    "ERROR_UNKNOWN" => "未知錯誤",
    "ERROR_DEAD_LINK" => "鏈接不可用",
    "ERROR_HTTP_LINK" => "鏈接不是http鏈接",
    "ERROR_HTTP_CONTENTTYPE" => "鏈接contentType不正確",
    "INVALID_URL" => "非法 URL",
    "INVALID_IP" => "非法 IP"
);

/**
 * 構(gòu)造函數(shù)
 * @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

// ossClient=new OssClient('你的keyid','你的密鑰','oss-cn-beijing.aliyuncs.com');ossClient=new OssClient('LTAIXGDThRhHGirb','qM8V53Ka8NK0jq7f7rfjwRcu9ekH9e','oss-cn-beijing.aliyuncs.com');
ossClient->uploadFile('xingpaipics', 'meeting_file/'.date ('Ym') .'/'.file['name'], file['tmp_name']);this->oriName = file['name'];this->fileSize = file['size'];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 (!$this->checkType()) {
        $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
        return;
    }

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

    //創(chuàng)建目錄失敗
    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;
    }

    preg_match('/(^https*:\/\/[^:\/]+)/', $imgUrl, $matches);
    $host_with_protocol = count($matches) > 1 ? $matches[1] : '';

    // 判斷是否是合法 url
    if (!filter_var($host_with_protocol, FILTER_VALIDATE_URL)) {
        $this->stateInfo = $this->getStateInfo("INVALID_URL");
        return;
    }

    preg_match('/^https*:\/\/(.+)/', $host_with_protocol, $matches);
    $host_without_protocol = count($matches) > 1 ? $matches[1] : '';

    // 此時提取出來的可能是 ip 也有可能是域名,先獲取 ip
    $ip = gethostbyname($host_without_protocol);
    // 判斷是否是私有 ip
    if(!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
        $this->stateInfo = $this->getStateInfo("INVALID_IP");
        return;
    }

    //獲取請求頭并檢測死鏈
    $heads = get_headers($imgUrl, 1);
    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']) || !isset($heads['Content-Type']) || !stristr($heads['Content-Type'], "image")) {
        $this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
        return;
    }

    //打開輸出緩沖區(qū)并獲取遠程圖片
    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;
    }

    //創(chuàng)建目錄失敗
    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 $rootPath . $fullname;
    //修改:替換路徑
    return $fullname;

// fullname =this->fullName;
// rootPath =_SERVER['DOCUMENT_ROOT'];
//
// if (substr(fullname, 0, 1) != '/') { //fullname = '/' . fullname; // } // // returnrootPath . $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
    );
}

}
2、config.json,注意,配置的圖片訪問路徑前綴和上傳保存路徑組合起來需要和oss上傳的路徑一樣,不然插入圖片后,圖片在編輯器里顯示不出來,因為圖片地址跟oss上的不一致,這個做的過程中自己調(diào)試就知道了。

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

/* 涂鴉圖片上傳配置項 */
"scrawlActionName": "uploadscrawl", /* 執(zhí)行上傳涂鴉的action名稱 */
"scrawlFieldName": "upfile", /* 提交的圖片表單名稱 */
"scrawlPathFormat": "/meeting_file/{yyyy}{mm}/{filename}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
"scrawlMaxSize": 52428800, /* 上傳大小限制,單位B */
"scrawlUrlPrefix": "http://xingpaipics.oss-cn-beijing.aliyuncs.com", /* 圖片訪問路徑前綴 */
"scrawlInsertAlign": "none",

/* 截圖工具上傳 */
"snapscreenActionName": "uploadimage", /* 執(zhí)行上傳截圖的action名稱 */
"snapscreenPathFormat": "/meeting_file/{yyyy}{mm}/{filename}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
"snapscreenUrlPrefix": "http://xingpaipics.oss-cn-beijing.aliyuncs.com", /* 圖片訪問路徑前綴 */
"snapscreenInsertAlign": "none", /* 插入的圖片浮動方式 */

/* 抓取遠程圖片配置 */
"catcherLocalDomain": ["127.0.0.1", "localhost", "img.baidu.com"],
"catcherActionName": "catchimage", /* 執(zhí)行抓取遠程圖片的action名稱 */
"catcherFieldName": "source", /* 提交的圖片列表表單名稱 */
"catcherPathFormat": "/meeting_file/{yyyy}{mm}/{filename}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
"catcherUrlPrefix": "http://xingpaipics.oss-cn-beijing.aliyuncs.com", /* 圖片訪問路徑前綴 */
"catcherMaxSize": 52428800, /* 上傳大小限制,單位B */
"catcherAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 抓取圖片格式顯示 */

/* 上傳視頻配置 */
"videoActionName": "uploadvideo", /* 執(zhí)行上傳視頻的action名稱 */
"videoFieldName": "upfile", /* 提交的視頻表單名稱 */
"videoPathFormat": "/meeting_file/{yyyy}{mm}/{filename}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
"videoUrlPrefix": "http://xingpaipics.oss-cn-beijing.aliyuncs.com", /* 視頻訪問路徑前綴 */
"videoMaxSize": 52428800, /* 上傳大小限制,單位B,默認100MB */
"videoAllowFiles": [
    ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
    ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"], /* 上傳視頻格式顯示 */

/* 上傳文件配置 */
"fileActionName": "uploadfile", /* controller里,執(zhí)行上傳視頻的action名稱 */
"fileFieldName": "upfile", /* 提交的文件表單名稱 */
"filePathFormat": "/meeting_file/{yyyy}{mm}/{filename}", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */
"fileUrlPrefix": "http://xingpaipics.oss-cn-beijing.aliyuncs.com", /* 文件訪問路徑前綴 */
"fileMaxSize": 52428800, /* 上傳大小限制,單位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", /* 執(zhí)行圖片管理的action名稱 */
"imageManagerListPath": "/meeting_file/", /* 指定要列出圖片的目錄 */
"imageManagerListSize": 20, /* 每次列出文件數(shù)量 */
"imageManagerUrlPrefix": "http://xingpaipics.oss-cn-beijing.aliyuncs.com", /* 圖片訪問路徑前綴 */
"imageManagerInsertAlign": "none", /* 插入的圖片浮動方式 */
"imageManagerAllowFiles": [".png", ".jpg", ".jpeg", ".gif", ".bmp"], /* 列出的文件類型 */

/* 列出指定目錄下的文件 */
"fileManagerActionName": "listfile", /* 執(zhí)行文件管理的action名稱 */
"fileManagerListPath": "/meeting_file/", /* 指定要列出文件的目錄 */
"fileManagerUrlPrefix": "http://xingpaipics.oss-cn-beijing.aliyuncs.com", /* 文件訪問路徑前綴 */
"fileManagerListSize": 20, /* 每次列出文件數(shù)量 */
"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"
] /* 列出的文件類型 */

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容