本文主要介绍了php版阿里云oss图片上传类,结合具体实例形式分析了php版阿里云oss图片上传类的功能、定义、使用方法与相关注意事项。需要的朋友可以参考下,希望对大家有所帮助。
具体如下:
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',// 子目录创建方式 可以使用hash date custom
'subdir' => '', // 子目录名称 subtype为custom方式后有效
'dateformat' => 'ymd',
'hashlevel' => 1, // hash的目录层次
'savepath' => '',// 上传文件保存路径
'autocheck' => true, // 是否自动检查附件
'uploadreplace' => false,// 存在同名是否覆盖
'saverule' => 'uniqid',// 上传文件命名规则
'hashtype' => 'md5_file',// 上传文件hash规则函数名
);
// 错误信息
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]);
}
/**
* 架构函数
* @access public
* @param array $config 上传参数
*/
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.主函数
/**
* 上传所有文件
* @access public
* @param string $savepath 上传文件保存路径
* @return string
*/
public function upload($savepath ='') {
//如果不指定保存文件名,则由系统默认
if(empty($savepath)) {
$savepath = $this->savepath;
}
$fileinfo = array();
$isupload = false;
// 获取上传的文件信息
// 对$_files数组信息处理
$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.核心处理函数
/**
* 上传一个文件
* @access public
* @param mixed $name 数据
* @param string $value 数据表名
* @return string
*/
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) {
// todo 对图片压缩包在线解压
}
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); // 计算缩放比例
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);
//png和gif的透明处理 by luofei614
if('png'==$type){
imagealphablending($thumbimg, false);//取消默认的混色模式(为解决阴影为绿色的问题)
imagesavealpha($thumbimg,true);//设定保存完整的 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);
}
}
// 复制图片
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;
}
return false;
}
5.辅助函数
/**
* 转换上传文件数组变量为正确的方式
* @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) {
//文件上传失败
//捕获错误代码
$this->error($file['error']);
return false;
}
//文件上传成功,进行自定义规则检查
//检查文件大小
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;
}
// 自动转换字符集 支持数组转换
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;
}
}
/**
* 检查上传的文件类型是否合法
* @access private
* @param string $type 数据
* @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 数据
* @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;
}
/**
* 取得最后一次错误信息
* @access public
* @return string
*/
public function geterrormsg() {
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);
相关推荐:
yii2.0整合阿里云oss如何删除单个文件的实例详解
详细介绍thinkphp简单导入和使用阿里云osssdk的方法
php应用七牛云的重定向上传和回调上传实例分享
以上就是php文件上传之阿里云oss的使用的详细内容。