php版阿里云OSS图片上传类详解
本文实例讲述了php版阿里云OSS图片上传类。分享给大家供大家参考,具体如下:
1.阿里云基本函数
/**
*把本地变量的内容到文件
*简单上传,上传指定变量的内存值作为object的内容
*/
publicfunctionputObject($imgPath,$object)
{
$content=file_get_contents($imgPath);//把当前文件的内容获取到传入文件中
$options=array();
try{
$this->ossClient->putObject($this->bucket,$object,$content,$options);
}catch(OssException$e){
return$e->getMessage();
}
returnTRUE;
}
/**
*上传指定的本地文件内容
*/
publicfunctionuploadFile($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();
}
returnTRUE;
}
//删除对象
publicfunctiondeleteObject($object){
try{
$this->ossClient->deleteObject($this->bucket,$object);
}catch(OssException$e){
return$e->getMessage();
}
returnTRUE;
}
//判断对象是否存在
publicfunctiondoesObjectExist($object){
try{
$result=$this->ossClient->doesObjectExist($this->bucket,$object);
}catch(OssException$e){
return$e->getMessage();
}
return$result;
}
//批量删除对象
publicfunctiondeleteObjects($objects){
try{
$this->ossClient->deleteObjects($this->bucket,$objects);
}catch(OssException$e){
return$e->getMessage();
}
returnTRUE;
}
/**
*获取object的内容
*
*@paramOssClient$ossClientOssClient实例
*@paramstring$bucket存储空间名称
*@returnnull
*/
publicfunctiongetObject($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',//子目录创建方式可以使用hashdatecustom
'subDir'=>'',//子目录名称subType为custom方式后有效
'dateFormat'=>'Ymd',
'hashLevel'=>1,//hash的目录层次
'savePath'=>'',//上传文件保存路径
'autoCheck'=>true,//是否自动检查附件
'uploadReplace'=>false,//存在同名是否覆盖
'saveRule'=>'uniqid',//上传文件命名规则
'hashType'=>'md5_file',//上传文件Hash规则函数名
);
//错误信息
private$error='';
//上传成功的文件信息
private$uploadFileInfo;
publicfunction__get($name){
if(isset($this->configinfo[$name])){
return$this->configinfo[$name];
}
returnnull;
}
publicfunction__set($name,$value){
if(isset($this->configinfo[$name])){
$this->configinfo[$name]=$value;
}
}
publicfunction__isset($name){
returnisset($this->configinfo[$name]);
}
/**
*架构函数
*@accesspublic
*@paramarray$config上传参数
*/
publicfunction__construct($config=array()){
if(is_array($config)){
$this->config=array_merge($this->config,$config);
}
$this->bucket=C('OSS_TEST_BUCKET');
$this->ossClient=newOssClient(C('OSS_ACCESS_ID'),C('OSS_ACCESS_KEY'),C('OSS_ENDPOINT'),false);
}
3.主函数
/**
*上传所有文件
*@accesspublic
*@paramstring$savePath上传文件保存路径
*@returnstring
*/
publicfunctionupload($savePath=''){
//如果不指定保存文件名,则由系统默认
if(empty($savePath)){
$savePath=$this->savePath;
}
$fileInfo=array();
$isUpload=false;
//获取上传的文件信息
//对$_FILES数组信息处理
$files=$this->dealFiles($_FILES);
foreach($filesas$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))
returnfalse;
}
//保存上传文件
if(!$this->save($file))returnfalse;
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;
returntrue;
}else{
$this->error='没有选择上传文件';
returnfalse;
}
}
4.核心处理函数
/**
*上传一个文件
*@accesspublic
*@parammixed$name数据
*@paramstring$value数据表名
*@returnstring
*/
privatefunctionsave($file){
$filename=$file['savepath'].$file['savename'];
if(!$this->uploadReplace&&$this->doesObjectExist($filename)){
//不覆盖同名文件
$this->error='文件已经存在!'.$filename;
returnfalse;
}
//如果是图像文件检测文件格式
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='非法图像文件';
returnfalse;
}
}
if(!$this->putObject($file['tmp_name'],$this->autoCharset($filename,'utf-8','gbk'))){
$this->error='文件上传保存错误!';
returnfalse;
}
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){
//TODO对图片压缩包在线解压
}
returntrue;
}
/**
*生成缩略图
*@static
*@accesspublic
*@paramstring$image原图
*@paramstring$type图像格式
*@paramstring$thumbname缩略图文件名
*@paramstring$maxWidth宽度
*@paramstring$maxHeight高度
*@paramstring$position缩略图保存目录
*@paramboolean$interlace启用隔行扫描
*@returnvoid
*/
publicfunctionthumb($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)){
returnfalse;
}
$srcImg=$createFun($image);
//创建缩略图
if($type!='gif'&&function_exists('imagecreatetruecolor'))
$thumbImg=imagecreatetruecolor($width,$height);
else
$thumbImg=imagecreate($width,$height);
//png和gif的透明处理byluofei614
if('png'==$type){
imagealphablending($thumbImg,false);//取消默认的混色模式(为解决阴影为绿色的问题)
imagesavealpha($thumbImg,true);//设定保存完整的alpha通道信息(为解决阴影为绿色的问题)
}elseif('gif'==$type){
$trnprt_indx=imagecolortransparent($srcImg);
if($trnprt_indx>=0){
//itstransparent
$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);
//对jpeg图形设置隔行扫描
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;
}
returnfalse;
}
5.辅助函数
/**
*转换上传文件数组变量为正确的方式
*@accessprivate
*@paramarray$files上传的文件变量
*@returnarray
*/
privatefunctiondealFiles($files){
$fileArray=array();
$n=0;
foreach($filesas$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($keysas$_key){
$fileArray[$n][$_key]=$file[$_key][$i];
}
$n++;
}
}else{
$fileArray[$key]=$file;
}
}
return$fileArray;
}
/**
*检查上传的文件
*@accessprivate
*@paramarray$file文件信息
*@returnboolean
*/
privatefunctioncheck($file){
if($file['error']!==0){
//文件上传失败
//捕获错误代码
$this->error($file['error']);
returnfalse;
}
//文件上传成功,进行自定义规则检查
//检查文件大小
if(!$this->checkSize($file['size'])){
$this->error='上传文件大小不符!';
returnfalse;
}
//检查文件Mime类型
if(!$this->checkType($file['type'])){
$this->error='上传文件MIME类型不允许!';
returnfalse;
}
//检查文件类型
if(!$this->checkExt($file['extension'])){
$this->error='上传文件类型不允许';
returnfalse;
}
//检查是否合法上传
if(!$this->checkUpload($file['tmp_name'])){
$this->error='非法上传文件!';
returnfalse;
}
returntrue;
}
//自动转换字符集支持数组转换
privatefunctionautoCharset($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')){
returnmb_convert_encoding($fContents,$to,$from);
}elseif(function_exists('iconv')){
returniconv($from,$to,$fContents);
}else{
return$fContents;
}
}
/**
*检查上传的文件类型是否合法
*@accessprivate
*@paramstring$type数据
*@returnboolean
*/
privatefunctioncheckType($type){
if(!empty($this->allowTypes))
returnin_array(strtolower($type),$this->allowTypes);
returntrue;
}
/**
*检查上传的文件后缀是否合法
*@accessprivate
*@paramstring$ext后缀名
*@returnboolean
*/
privatefunctioncheckExt($ext){
if(!empty($this->allowExts))
returnin_array(strtolower($ext),$this->allowExts,true);
returntrue;
}
/**
*检查文件大小是否合法
*@accessprivate
*@paraminteger$size数据
*@returnboolean
*/
privatefunctioncheckSize($size){
return!($size>$this->maxSize)||(-1==$this->maxSize);
}
/**
*检查文件是否非法提交
*@accessprivate
*@paramstring$filename文件名
*@returnboolean
*/
privatefunctioncheckUpload($filename){
returnis_uploaded_file($filename);
}
/**
*取得上传文件的后缀
*@accessprivate
*@paramstring$filename文件名
*@returnboolean
*/
privatefunctiongetExt($filename){
$pathinfo=pathinfo($filename);
return$pathinfo['extension'];
}
/**
*取得上传文件的信息
*@accesspublic
*@returnarray
*/
publicfunctiongetUploadFileInfo(){
return$this->uploadFileInfo;
}
/**
*取得最后一次错误信息
*@accesspublic
*@returnstring
*/
publicfunctiongetErrorMsg(){
return$this->error;
}
总结:与普通上传的区别在于,它是全部通过阿里云的oss接口来处理文件保存的。普通上传是把本地文件移动到服务器上,而它则是把文件移动到阿里云服务器上。
缩略图思路:
a.上传图片至服务器
b.获取图片进行处理
c.上传处理好的图片至服务器
d.根据配置,删除或者不删除服务器的原图(OSS)
imagePNG($thumbImg,'Uploads/file.png');//中转站
//生成图片
$this->putObject('Uploads/file.png',$thumbname);
unlink('Uploads/file.png');
imagedestroy($thumbImg);
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP图形与图片操作技巧汇总》、《php文件操作总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php面向对象程序设计入门教程》、《PHP网络编程技巧总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。