最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

php版阿里云OSS圖片上傳類詳解

 更新時(shí)間:2016年12月01日 10:16:31   作者:牛逼的霍嘯林  
這篇文章主要介紹了php版阿里云OSS圖片上傳類,結(jié)合具體實(shí)例形式分析了php版阿里云OSS圖片上傳類的功能、定義、使用方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了php版阿里云OSS圖片上傳類。分享給大家供大家參考,具體如下:

1.阿里云基本函數(shù)

/**
 * 把本地變量的內(nèi)容到文件
 * 簡(jiǎn)單上傳,上傳指定變量的內(nèi)存值作為object的內(nèi)容
 */
public function putObject($imgPath,$object)
{
  $content = file_get_contents($imgPath); // 把當(dāng)前文件的內(nèi)容獲取到傳入文件中
  $options = array();
  try {
    $this->ossClient->putObject($this->bucket, $object, $content, $options);
  } catch (OssException $e) {
    return $e->getMessage();
  }
  return TRUE;
}
/**
 * 上傳指定的本地文件內(nèi)容
 */
public function uploadFile($imgPath,$object) //$_FILES['img']['tmp_name']
{
  $filePath = $imgPath;
  $options = array();
  try {
    $this->ossClient->uploadFile($this->bucket, $object, $filePath, $options);
  } catch (OssException $e) {
    return $e->getMessage();
  }
  return TRUE;
}
// 刪除對(duì)象
public function deleteObject($object) {
  try {
    $this->ossClient->deleteObject($this->bucket, $object);
  } catch (OssException $e) {
    return $e->getMessage();
  }
  return TRUE;
}
// 判斷對(duì)象是否存在
public function doesObjectExist($object) {
  try {
    $result = $this->ossClient->doesObjectExist($this->bucket, $object);
  } catch (OssException $e) {
    return $e->getMessage();
  }
  return $result;
}
// 批量刪除對(duì)象
public function deleteObjects($objects) {
  try {
    $this->ossClient->deleteObjects($this->bucket, $objects);
  } catch (OssException $e) {
    return $e->getMessage();
  }
  return TRUE;
}
/**
 * 獲取object的內(nèi)容
 *
 * @param OssClient $ossClient OssClient實(shí)例
 * @param string $bucket 存儲(chǔ)空間名稱
 * @return null
 */
public function getObject($object)
{
  $options = array();
  try {
    $content = $this->ossClient->getObject($this->bucket, $object, $options);
  } catch (OssException $e) {
    return $e->getMessage();
  }
  // file_get_contents
  return $content;
}

2.基本配置與輔助函數(shù)

public $ossClient,$bucket;
private $configinfo =  array(
  'maxSize'      => -1,  // 上傳文件的最大值
  'supportMulti'   => true,  // 是否支持多文件上傳
  'allowExts'     => array(),  // 允許上傳的文件后綴 留空不作后綴檢查
  'allowTypes'    => array(),  // 允許上傳的文件類型 留空不做檢查
  'thumb'       => false,  // 使用對(duì)上傳圖片進(jìn)行縮略圖處理
  'imageClassPath'  => 'ORG.Util.Image',  // 圖庫類包路徑
  'thumbMaxWidth'   => '',// 縮略圖最大寬度
  'thumbMaxHeight'  => '',// 縮略圖最大高度
  'thumbPrefix'    => 'thumb_',// 縮略圖前綴
  'thumbSuffix'    => '',
  'thumbPath'     => '',// 縮略圖保存路徑
  'thumbFile'     => '',// 縮略圖文件名
  'thumbExt'     => '',// 縮略圖擴(kuò)展名
  'thumbRemoveOrigin' => false,// 是否移除原圖
  'zipImages'     => false,// 壓縮圖片文件上傳
  'autoSub'      => false,// 啟用子目錄保存文件
  'subType'      => 'hash',// 子目錄創(chuàng)建方式 可以使用hash date custom
  'subDir'      => '', // 子目錄名稱 subType為custom方式后有效
  'dateFormat'    => 'Ymd',
  'hashLevel'     => 1, // hash的目錄層次
  'savePath'     => '',// 上傳文件保存路徑
  'autoCheck'     => true, // 是否自動(dòng)檢查附件
  'uploadReplace'   => false,// 存在同名是否覆蓋
  'saveRule'     => 'uniqid',// 上傳文件命名規(guī)則
  'hashType'     => 'md5_file',// 上傳文件Hash規(guī)則函數(shù)名
  );
// 錯(cuò)誤信息
private $error = '';
// 上傳成功的文件信息
private $uploadFileInfo ;
public function __get($name){
  if(isset($this->configinfo[$name])) {
    return $this->configinfo[$name];
  }
  return null;
}
public function __set($name,$value){
  if(isset($this->configinfo[$name])) {
    $this->configinfo[$name]  =  $value;
  }
}
public function __isset($name){
  return isset($this->configinfo[$name]);
}
/**
 * 架構(gòu)函數(shù)
 * @access public
 * @param array $config 上傳參數(shù)
 */
public function __construct($config=array()) {
  if(is_array($config)) {
    $this->config  =  array_merge($this->config,$config);
  }
  $this->bucket = C('OSS_TEST_BUCKET');
  $this->ossClient = new OssClient(C('OSS_ACCESS_ID'), C('OSS_ACCESS_KEY'), C('OSS_ENDPOINT'), false);
}

3.主函數(shù)

/**
 * 上傳所有文件
 * @access public
 * @param string $savePath 上傳文件保存路徑
 * @return string
 */
public function upload($savePath ='') {
  //如果不指定保存文件名,則由系統(tǒng)默認(rèn)
  if(empty($savePath)) {
    $savePath = $this->savePath;
  }
  $fileInfo  = array();
  $isUpload  = false;
  // 獲取上傳的文件信息
  // 對(duì)$_FILES數(shù)組信息處理
  $files  =  $this->dealFiles($_FILES);
  foreach($files as $key => $file) {
    //過濾無效的上傳
    if(!empty($file['name'])) {
      //登記上傳文件的擴(kuò)展信息
      if(!isset($file['key']))  $file['key']  =  $key;
      $file['extension'] =  $this->getExt($file['name']);
      $file['savepath']  =  $savePath;
      $file['savename']  =  $this->getSaveName($file);
      // 自動(dòng)檢查附件
      if($this->autoCheck) {
        if(!$this->check($file))
          return false;
      }
      //保存上傳文件
      if(!$this->save($file)) return false;
      if(function_exists($this->hashType)) {
        $fun = $this->hashType;
        $file['hash']  = $fun($this->autoCharset($file['savepath'].$file['savename'],'utf-8','gbk'));
      }
      //上傳成功后保存文件信息,供其他地方調(diào)用
      unset($file['tmp_name'],$file['error']);
      $fileInfo[] = $file;
      $isUpload  = true;
    }
  }
  if($isUpload) {
    $this->uploadFileInfo = $fileInfo;
    return true;
  }else {
    $this->error = '沒有選擇上傳文件';
    return false;
  }
}

4.核心處理函數(shù)

/**
 * 上傳一個(gè)文件
 * @access public
 * @param mixed $name 數(shù)據(jù)
 * @param string $value 數(shù)據(jù)表名
 * @return string
 */
private function save($file) {
  $filename = $file['savepath'].$file['savename'];
  if(!$this->uploadReplace && $this->doesObjectExist($filename)) {
    // 不覆蓋同名文件
    $this->error  =  '文件已經(jīng)存在!'.$filename;
    return false;
  }
  // 如果是圖像文件 檢測(cè)文件格式
  if( in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png','swf'))) {
    $info  = getimagesize($file['tmp_name']);
    if(false === $info || ('gif' == strtolower($file['extension']) && empty($info['bits']))){
      $this->error = '非法圖像文件';
      return false;
    }
  }
  if(!$this->putObject($file['tmp_name'], $this->autoCharset($filename,'utf-8','gbk'))) {
    $this->error = '文件上傳保存錯(cuò)誤!';
    return false;
  }
  if($this->thumb && in_array(strtolower($file['extension']),array('gif','jpg','jpeg','bmp','png'))) {
    $image = getimagesize(C('OSS_IMG_URL').'/'.$filename);
    if(false !== $image) {
      //是圖像文件生成縮略圖
      $thumbWidth   =  explode(',',$this->thumbMaxWidth);
      $thumbHeight  =  explode(',',$this->thumbMaxHeight);
      $thumbPrefix  =  explode(',',$this->thumbPrefix);
      $thumbSuffix  =  explode(',',$this->thumbSuffix);
      $thumbFile   =  explode(',',$this->thumbFile);
      $thumbPath   =  $this->thumbPath?$this->thumbPath:dirname($filename).'/';
      $thumbExt    =  $this->thumbExt ? $this->thumbExt : $file['extension']; //自定義縮略圖擴(kuò)展名
      // 生成圖像縮略圖
      import($this->imageClassPath);
      for($i=0,$len=count($thumbWidth); $i<$len; $i++) {
        if(!empty($thumbFile[$i])) {
          $thumbname =  $thumbFile[$i];
        }else{
          $prefix   =  isset($thumbPrefix[$i])?$thumbPrefix[$i]:$thumbPrefix[0];
          $suffix   =  isset($thumbSuffix[$i])?$thumbSuffix[$i]:$thumbSuffix[0];
          $thumbname =  $prefix.basename($filename,'.'.$file['extension']).$suffix;
        }
        $this->thumb(C('OSS_IMG_URL').'/'.$filename,$thumbPath.$thumbname.'.'.$thumbExt,'',$thumbWidth[$i],$thumbHeight[$i],true);
      }
      if($this->thumbRemoveOrigin) {
        // 生成縮略圖之后刪除原圖
        $this->deleteObject($filename);
      }
    }
  }
  if($this->zipImags) {
    // TODO 對(duì)圖片壓縮包在線解壓
  }
  return true;
}
/**
 * 生成縮略圖
 * @static
 * @access public
 * @param string $image 原圖
 * @param string $type 圖像格式
 * @param string $thumbname 縮略圖文件名
 * @param string $maxWidth 寬度
 * @param string $maxHeight 高度
 * @param string $position 縮略圖保存目錄
 * @param boolean $interlace 啟用隔行掃描
 * @return void
 */
public function thumb($image, $thumbname, $type='', $maxWidth=200, $maxHeight=50, $interlace=true) {
  // 獲取原圖信息
  $info = Image::getImageInfo($image);
  if ($info !== false) {
    $srcWidth = $info['width'];
    $srcHeight = $info['height'];
    $type = empty($type) ? $info['type'] : $type;
    $type = strtolower($type);
    $interlace = $interlace ? 1 : 0;
    unset($info);
    $scale = min($maxWidth / $srcWidth, $maxHeight / $srcHeight); // 計(jì)算縮放比例
    if ($scale >= 1) {
      // 超過原圖大小不再縮略
      $width = $srcWidth;
      $height = $srcHeight;
    } else {
      // 縮略圖尺寸
      $width = (int) ($srcWidth * $scale);
      $height = (int) ($srcHeight * $scale);
    }
    // 載入原圖
    $createFun = 'ImageCreateFrom' . ($type == 'jpg' ? 'jpeg' : $type);
    if(!function_exists($createFun)) {
      return false;
    }
    $srcImg = $createFun($image);
    //創(chuàng)建縮略圖
    if ($type != 'gif' && function_exists('imagecreatetruecolor'))
      $thumbImg = imagecreatetruecolor($width, $height);
    else
      $thumbImg = imagecreate($width, $height);
     //png和gif的透明處理 by luofei614
    if('png'==$type){
      imagealphablending($thumbImg, false);//取消默認(rèn)的混色模式(為解決陰影為綠色的問題)
      imagesavealpha($thumbImg,true);//設(shè)定保存完整的 alpha 通道信息(為解決陰影為綠色的問題)
    }elseif('gif'==$type){
      $trnprt_indx = imagecolortransparent($srcImg);
       if ($trnprt_indx >= 0) {
          //its transparent
          $trnprt_color = imagecolorsforindex($srcImg , $trnprt_indx);
          $trnprt_indx = imagecolorallocate($thumbImg, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
          imagefill($thumbImg, 0, 0, $trnprt_indx);
          imagecolortransparent($thumbImg, $trnprt_indx);
     }
    }
    // 復(fù)制圖片
    if (function_exists("ImageCopyResampled"))
      imagecopyresampled($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
    else
      imagecopyresized($thumbImg, $srcImg, 0, 0, 0, 0, $width, $height, $srcWidth, $srcHeight);
    // 對(duì)jpeg圖形設(shè)置隔行掃描
    if ('jpg' == $type || 'jpeg' == $type)
      imageinterlace($thumbImg, $interlace);
    imagePNG($thumbImg,'Uploads/file.png'); // 中轉(zhuǎn)站
    // 生成圖片
    $this->putObject('Uploads/file.png',$thumbname);
    imagedestroy($thumbImg);
    imagedestroy($srcImg);
    return $thumbname;
  }
  return false;
}

5.輔助函數(shù)

/**
* 轉(zhuǎn)換上傳文件數(shù)組變量為正確的方式
* @access private
* @param array $files 上傳的文件變量
* @return array
*/
private function dealFiles($files) {
    $fileArray = array();
    $n     = 0;
    foreach ($files as $key=>$file){
      if(is_array($file['name'])) {
        $keys    =  array_keys($file);
        $count   =  count($file['name']);
        for ($i=0; $i<$count; $i++) {
          $fileArray[$n]['key'] = $key;
          foreach ($keys as $_key){
            $fileArray[$n][$_key] = $file[$_key][$i];
          }
          $n++;
        }
      }else{
        $fileArray[$key] = $file;
      }
    }
    return $fileArray;
}
/**
* 檢查上傳的文件
* @access private
* @param array $file 文件信息
* @return boolean
*/
private function check($file) {
    if($file['error']!== 0) {
      //文件上傳失敗
      //捕獲錯(cuò)誤代碼
      $this->error($file['error']);
      return false;
    }
    //文件上傳成功,進(jìn)行自定義規(guī)則檢查
    //檢查文件大小
    if(!$this->checkSize($file['size'])) {
      $this->error = '上傳文件大小不符!';
      return false;
    }
    //檢查文件Mime類型
    if(!$this->checkType($file['type'])) {
      $this->error = '上傳文件MIME類型不允許!';
      return false;
    }
    //檢查文件類型
    if(!$this->checkExt($file['extension'])) {
      $this->error ='上傳文件類型不允許';
      return false;
    }
    //檢查是否合法上傳
    if(!$this->checkUpload($file['tmp_name'])) {
      $this->error = '非法上傳文件!';
      return false;
    }
    return true;
}
// 自動(dòng)轉(zhuǎn)換字符集 支持?jǐn)?shù)組轉(zhuǎn)換
private function autoCharset($fContents, $from='gbk', $to='utf-8') {
    $from  = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
    $to   = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
      //如果編碼相同或者非字符串標(biāo)量則不轉(zhuǎn)換
      return $fContents;
    }
    if (function_exists('mb_convert_encoding')) {
      return mb_convert_encoding($fContents, $to, $from);
    } elseif (function_exists('iconv')) {
      return iconv($from, $to, $fContents);
    } else {
      return $fContents;
    }
}
/**
* 檢查上傳的文件類型是否合法
* @access private
* @param string $type 數(shù)據(jù)
* @return boolean
*/
private function checkType($type) {
    if(!empty($this->allowTypes))
      return in_array(strtolower($type),$this->allowTypes);
    return true;
}
/**
* 檢查上傳的文件后綴是否合法
* @access private
* @param string $ext 后綴名
* @return boolean
*/
private function checkExt($ext) {
    if(!empty($this->allowExts))
      return in_array(strtolower($ext),$this->allowExts,true);
    return true;
}
/**
* 檢查文件大小是否合法
* @access private
* @param integer $size 數(shù)據(jù)
* @return boolean
*/
private function checkSize($size) {
    return !($size > $this->maxSize) || (-1 == $this->maxSize);
}
/**
* 檢查文件是否非法提交
* @access private
* @param string $filename 文件名
* @return boolean
*/
private function checkUpload($filename) {
    return is_uploaded_file($filename);
}
/**
* 取得上傳文件的后綴
* @access private
* @param string $filename 文件名
* @return boolean
*/
private function getExt($filename) {
    $pathinfo = pathinfo($filename);
    return $pathinfo['extension'];
}
/**
* 取得上傳文件的信息
* @access public
* @return array
*/
public function getUploadFileInfo() {
    return $this->uploadFileInfo;
}
/**
* 取得最后一次錯(cuò)誤信息
* @access public
* @return string
*/
public function getErrorMsg() {
    return $this->error;
}

總結(jié):與普通上傳的區(qū)別在于,它是全部通過阿里云的oss接口來處理文件保存的。普通上傳是把本地文件移動(dòng)到服務(wù)器上,而它則是把文件移動(dòng)到阿里云服務(wù)器上。

縮略圖思路:

a.上傳圖片至服務(wù)器
b.獲取圖片進(jìn)行處理
c.上傳處理好的圖片至服務(wù)器
d.根據(jù)配置,刪除或者不刪除服務(wù)器的原圖(OSS)

imagePNG($thumbImg,'Uploads/file.png'); // 中轉(zhuǎn)站
// 生成圖片
$this->putObject('Uploads/file.png',$thumbname);
unlink('Uploads/file.png');
imagedestroy($thumbImg);

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP圖形與圖片操作技巧匯總》、《php文件操作總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總

希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • php如何比較兩個(gè)浮點(diǎn)數(shù)是否相等詳解

    php如何比較兩個(gè)浮點(diǎn)數(shù)是否相等詳解

    這篇文章主要給大家介紹了關(guān)于php如何比較兩個(gè)浮點(diǎn)數(shù)是否相等的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-02-02
  • php實(shí)現(xiàn)圖片按比例截取的方法

    php實(shí)現(xiàn)圖片按比例截取的方法

    這篇文章主要介紹了php實(shí)現(xiàn)圖片按比例截取的方法,涉及php針對(duì)圖形的讀取、運(yùn)算及生成相關(guān)操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2017-02-02
  • 解析posix與perl標(biāo)準(zhǔn)的正則表達(dá)式區(qū)別

    解析posix與perl標(biāo)準(zhǔn)的正則表達(dá)式區(qū)別

    本篇文章是對(duì)posix與perl標(biāo)準(zhǔn)的正則表達(dá)式區(qū)別進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
    2013-06-06
  • php+mysql查詢優(yōu)化簡(jiǎn)單實(shí)例

    php+mysql查詢優(yōu)化簡(jiǎn)單實(shí)例

    這篇文章主要介紹了php+mysql查詢優(yōu)化簡(jiǎn)單實(shí)例,分析了php+mysql程序設(shè)計(jì)中關(guān)于SQL語句優(yōu)化查詢的技巧,對(duì)于提高查詢效率有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-01-01
  • wordpress之wp-settings.php

    wordpress之wp-settings.php

    wordpress之wp-settings.php...
    2007-08-08
  • CodeIgniter基本配置詳細(xì)介紹

    CodeIgniter基本配置詳細(xì)介紹

    CodeIgniter 基本配置信息在 application/config/config.php 文件,本文詳細(xì)講解每一個(gè)基本配置選項(xiàng),從而快速掌握CodeIgniter 進(jìn)行開發(fā)。
    2013-11-11
  • CodeIgniter 完美解決URL含有中文字符串

    CodeIgniter 完美解決URL含有中文字符串

    下面小編就為大家?guī)硪黄狢odeIgniter 完美解決URL含有中文字符串。小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-05-05
  • PHP獲取文件相對(duì)路徑的方法

    PHP獲取文件相對(duì)路徑的方法

    這篇文章主要介紹了PHP獲取文件相對(duì)路徑的方法,通過自定義函數(shù)實(shí)現(xiàn)獲取文件相對(duì)路徑的功能,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-02-02
  • php 中文字符入庫或顯示亂碼問題的解決方法

    php 中文字符入庫或顯示亂碼問題的解決方法

    這個(gè)的問題就出在在php里沒有告訴mysql數(shù)據(jù)庫你要插入的數(shù)據(jù)是gbk類型的,要解決其實(shí)很簡(jiǎn)單。連接數(shù)據(jù)庫后加上這么一句話就OK了。
    2010-04-04
  • php Smarty date_format [格式化時(shí)間日期]

    php Smarty date_format [格式化時(shí)間日期]

    php Smarty date_format [格式化時(shí)間日期] ,需要的朋友可以參考下。
    2010-03-03

最新評(píng)論

庄河市| 大安市| 海林市| 崇信县| 蓝田县| 千阳县| 清远市| 宣恩县| 仪征市| 青冈县| 乌审旗| 乌拉特后旗| 新津县| 湖北省| 舒城县| 武强县| 清苑县| 铜川市| 长宁县| 凌海市| 遵义县| 疏附县| 商丘市| 芜湖市| 清原| 綦江县| 上栗县| 宝坻区| 攀枝花市| 闵行区| 汾西县| 梁山县| 兴海县| 龙海市| 三都| 万年县| 油尖旺区| 稻城县| 广宗县| 广东省| 万州区|