1.阿里云基本函数
/**
* 把本地变量的内容到文件
* 简单上传,上传指定变量的内存值作为object的内容
*/
public function putObject($imgPath,$object)
{
$content = file_get_contents($imgPath); // 把当前文件的内容获取到传入文件中
$options = array();
try {
$this->ossClient->putObject($this->bucket, $object, $content, $options);
} catch (OssException $e) {
return $e->getMessage();
}
return TRUE;
}
/**
* 上传指定的本地文件内容
*/
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;
}
// 删除对象
public function deleteObject($object) {
try {
$this->ossClient->deleteObject($this->bucket, $object);
} catch (OssException $e) {
return $e->getMessage();
}
return TRUE;
}
// 判断对象是否存在
public function doesObjectExist($object) {
try {
$result = $this->ossClient->doesObjectExist($this->bucket, $object);
} catch (OssException $e) {
return $e->getMessage();
}
return $result;
}
// 批量删除对象
public function deleteObjects($objects) {
try {
$this->ossClient->deleteObjects($this->bucket, $objects);
} catch (OssException $e) {
return $e->getMessage();
}
return TRUE;
}
/**
* 获取object的内容
*
* @param OssClient $ossClient OssClient实例
* @param string $bucket 存储空间名称
* @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.基本配置与辅助函数
public $ossClient,$bucket;
private $configinfo = array(
'maxSize' => -1,
'supportMulti' => true,
'allowExts' => array(),
'allowTypes' => array(),
'thumb' => false,
'imageClassPath' => 'ORG.Util.Image',
'thumbMaxWidth' => '',
'thumbMaxHeight' => '',
'thumbPrefix' => 'thumb_',
'thumbSuffix' => '',
'thumbPath' => '',
'thumbFile' => '',
'thumbExt' => '',
'thumbRemoveOrigin' => false,
'zipImages' => false,
'autoSub' => false,
'subType' => 'hash',
'subDir' => '',
'dateFormat' => 'Ymd',
'hashLevel' => 1,
'savePath' => '',
'autoCheck' => true,
'uploadReplace' => false,
'saveRule' => 'uniqid',
'hashType' => 'md5_file',
);
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]);
}
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.主函数
public function upload($savePath ='') {
if(empty($savePath)) {
$savePath = $this->savePath;
}
$fileInfo = array();
$isUpload = false;
$files = $this->dealFiles($_FILES);
foreach($files as $key => $file) {
if(!empty($file['name'])) {
if(!isset($file['key'])) $file['key'] = $key;
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
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'));
}
unset($file['tmp_name'],$file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if($isUpload) {
$this->uploadFileInfo = $fileInfo;
return true;
}else {
$this->error = '没有选择上传文件';
return false;
}
}
4.核心处理函数
private function save($file) {
$filename = $file['savepath'].$file['savename'];
if(!$this->uploadReplace && $this->doesObjectExist($filename)) {
$this->error = '文件已经存在!'.$filename;
return false;
}
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 = '文件上传保存错误!';
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'];
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) {
}
return true;
}
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);
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);
if ($type != 'gif' && function_exists('imagecreatetruecolor'))
$thumbImg = imagecreatetruecolor($width, $height);
else
$thumbImg = imagecreate($width, $height);
if('png'==$type){
imagealphablending($thumbImg, false);
imagesavealpha($thumbImg,true);
}elseif('gif'==$type){
$trnprt_indx = imagecolortransparent($srcImg);
if ($trnprt_indx >= 0) {
$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);
}
}
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);
if ('jpg' == $type || 'jpeg' == $type)
imageinterlace($thumbImg, $interlace);
imagePNG($thumbImg,'Uploads/file.png');
$this->putObject('Uploads/file.png',$thumbname);
imagedestroy($thumbImg);
imagedestroy($srcImg);
return $thumbname;
}
return false;
}
5.辅助函数
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;
}
private function check($file) {
if($file['error']!== 0) {
$this->error($file['error']);
return false;
}
if(!$this->checkSize($file['size'])) {
$this->error = '上传文件大小不符!';
return false;
}
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;
}
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))) {
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;
}
}
private function checkType($type) {
if(!empty($this->allowTypes))
return in_array(strtolower($type),$this->allowTypes);
return true;
}
private function checkExt($ext) {
if(!empty($this->allowExts))
return in_array(strtolower($ext),$this->allowExts,true);
return true;
}
private function checkSize($size) {
return !($size > $this->maxSize) || (-1 == $this->maxSize);
}
private function checkUpload($filename) {
return is_uploaded_file($filename);
}
private function getExt($filename) {
$pathinfo = pathinfo($filename);
return $pathinfo['extension'];
}
public function getUploadFileInfo() {
return $this->uploadFileInfo;
}
public function getErrorMsg() {
return $this->error;
}
总结:与普通上传的区别在于,它是全部通过阿里云的oss接口来处理文件保存的。普通上传是把本地文件移动到服务器上,而它则是把文件移动到阿里云服务器上。
缩略图思路,
a.上传图片至服务器
b.获取图片进行处理
c.上传处理好的图片至服务器
d.根据配置,删除或者不删除服务器的原图(OSS)
'Uploads/file.png''Uploads/file.png''Uploads/file.png'