热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

阿里云OSS图片上传类

1.阿里云基本函数***把本地变量的内容到文件*简单上传,上传指定变量的内存值作为object的内容*publicfunctionputObject($imgPath,$

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);

推荐阅读
  • PatchODAX8: ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • Windows7 64位系统安装PLSQL Developer的步骤和注意事项
    本文介绍了在Windows7 64位系统上安装PLSQL Developer的步骤和注意事项。首先下载并安装PLSQL Developer,注意不要安装在默认目录下。然后下载Windows 32位的oracle instant client,并解压到指定路径。最后,按照自己的喜好对解压后的文件进行命名和压缩。 ... [详细]
  • 本文介绍了在Python张量流中使用make_merged_spec()方法合并设备规格对象的方法和语法,以及参数和返回值的说明,并提供了一个示例代码。 ... [详细]
  • Todayatworksomeonetriedtoconvincemethat:今天在工作中有人试图说服我:{$obj->getTableInfo()}isfine ... [详细]
  • 手把手教你使用GraphPad Prism和Excel绘制回归分析结果的森林图
    本文介绍了使用GraphPad Prism和Excel绘制回归分析结果的森林图的方法。通过展示森林图,可以更加直观地将回归分析结果可视化。GraphPad Prism是一款专门为医学专业人士设计的绘图软件,同时也兼顾统计分析的功能,操作便捷,可以帮助科研人员轻松绘制出高质量的专业图形。文章以一篇发表在JACC杂志上的研究为例,利用其中的多因素回归分析结果来绘制森林图。通过本文的指导,读者可以学会如何使用GraphPad Prism和Excel绘制回归分析结果的森林图。 ... [详细]
  • 本文介绍了在实现了System.Collections.Generic.IDictionary接口的泛型字典类中如何使用foreach循环来枚举字典中的键值对。同时还讨论了非泛型字典类和泛型字典类在foreach循环中使用的不同类型,以及使用KeyValuePair类型在foreach循环中枚举泛型字典类的优势。阅读本文可以帮助您更好地理解泛型字典类的使用和性能优化。 ... [详细]
  • 花瓣|目标值_Compose 动画边学边做夏日彩虹
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了Compose动画边学边做-夏日彩虹相关的知识,希望对你有一定的参考价值。引言Comp ... [详细]
  • Java在运行已编译完成的类时,是通过java虚拟机来装载和执行的,java虚拟机通过操作系统命令JAVA_HOMEbinjava–option来启 ... [详细]
  • Redis底层数据结构之压缩列表的介绍及实现原理
    本文介绍了Redis底层数据结构之压缩列表的概念、实现原理以及使用场景。压缩列表是Redis为了节约内存而开发的一种顺序数据结构,由特殊编码的连续内存块组成。文章详细解释了压缩列表的构成和各个属性的含义,以及如何通过指针来计算表尾节点的地址。压缩列表适用于列表键和哈希键中只包含少量小整数值和短字符串的情况。通过使用压缩列表,可以有效减少内存占用,提升Redis的性能。 ... [详细]
  • 本文讨论了在手机移动端如何使用HTML5和JavaScript实现视频上传并压缩视频质量,或者降低手机摄像头拍摄质量的问题。作者指出HTML5和JavaScript无法直接压缩视频,只能通过将视频传送到服务器端由后端进行压缩。对于控制相机拍摄质量,只有使用JAVA编写Android客户端才能实现压缩。此外,作者还解释了在交作业时使用zip格式压缩包导致CSS文件和图片音乐丢失的原因,并提供了解决方法。最后,作者还介绍了一个用于处理图片的类,可以实现图片剪裁处理和生成缩略图的功能。 ... [详细]
  • 第四章高阶函数(参数传递、高阶函数、lambda表达式)(python进阶)的讲解和应用
    本文主要讲解了第四章高阶函数(参数传递、高阶函数、lambda表达式)的相关知识,包括函数参数传递机制和赋值机制、引用传递的概念和应用、默认参数的定义和使用等内容。同时介绍了高阶函数和lambda表达式的概念,并给出了一些实例代码进行演示。对于想要进一步提升python编程能力的读者来说,本文将是一个不错的学习资料。 ... [详细]
  • 本文介绍了200个经典c语言源代码,包括函数的使用,如sqrt函数、clanguagefunct等。这些源代码可以帮助读者更好地理解c语言的编程方法,并提供了实际应用的示例。 ... [详细]
  • Hibernate延迟加载深入分析-集合属性的延迟加载策略
    本文深入分析了Hibernate延迟加载的机制,特别是集合属性的延迟加载策略。通过延迟加载,可以降低系统的内存开销,提高Hibernate的运行性能。对于集合属性,推荐使用延迟加载策略,即在系统需要使用集合属性时才从数据库装载关联的数据,避免一次加载所有集合属性导致性能下降。 ... [详细]
  • Sleuth+zipkin链路追踪SpringCloud微服务的解决方案
    在庞大的微服务群中,随着业务扩展,微服务个数增多,系统调用链路复杂化。Sleuth+zipkin是解决SpringCloud微服务定位和追踪的方案。通过TraceId将不同服务调用的日志串联起来,实现请求链路跟踪。通过Feign调用和Request传递TraceId,将整个调用链路的服务日志归组合并,提供定位和追踪的功能。 ... [详细]
author-avatar
好人___夏洁
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有