• 阿里云对象存储 OSS-base64 上传图片


    原地址:https://help.aliyun.com/document_detail/88473.html?spm=a2c4g.11186623.6.1090.316c145eysHW9d

    方法封装:  
    public function uploads(Request $request)
    {
    	$pictrue = ''; // 获取图片转base64的字符串
    	$result = [];
    	// 转化base64编码图片 jpeg、jpg、png、bmp、gif
    	if(preg_match('/^(data:s*image/(w+);base64,)/', $pictrue, $result)) {
    		$type = $result[2]; // 获取图片类型
    		if(in_array($type, array('pjpeg','jpeg','jpg','bmp','png'))) {
    			// 图片名字                
    			$fileName = time().rand(1,1000).'.'.$type; // 图片名称
    			// 临时文件
    			$tmpfname = tempname("./image/", "FOO"); // windows
    			$tmpfname = ('/tmp/', 'FOO'); // linux
    			// 保存图片
    			$handle = fopen($tmpfname, "w");
    
    			// return [$pic, $result];
    			$object = 'school/avatar/'.date('Y/m/d').'/'.$fileName; // 阿里云上传地址
    			if (fwrite($handle, base64_decode(str_replace($result[1], '', $pic)))) 
    			{
    				// 上传图片至阿里云OSS
    				$ossClient = new Aliyunoss();
    				$data = $ossClient->uploads($object, $tmpfname);
    				// return [$pic, $result, $data];
    				// 关闭缓存
    				fclose($handle);
    				// 删除本地该图片
    				unlink($tmpfname);
    				// 返回图片链接
    				return StatusCode::getCode(0, ['data' => $data]);
    			}else {
    				return response(['message'=>'图片上传失败'], 200);
    			}
    
    		}else {
    			return response(['message'=>'图片类型错误'], 200);
    		}                    
    	} else {
    		return response(['message'=>'图片编码错误'], 200);
    	}
    }
    

      

    阿里云OSS
    public function uploads($object, $content)
    {
    	$ossClient = self::getOssClient();
    	if (is_null($ossClient)) exit(1);
    	$bucket = self::getBucketName();
    	try{
    		$ossClient->uploadFile($bucket, $object, $content);
    	} catch(OssException $e) {
    		self::println(__FUNCTION__ . ": FAILED
    ");
    		self::println($e->getMessage() . "
    ");
    		$object = 'error';
    	}
    	return $object;
    }
    

      

  • 相关阅读:
    keras:InternalError: Failed to create session
    centos 常用命令
    centos7 安装gdal2.3.1
    centos mysql初探 -- 配置、基本操作及问题
    machine learning 之 Recommender Systems
    machine learning 之 Anomaly detection
    centos R包 tidyverse安装
    centos 问题解决记录
    R python在无图形用户界面时保存图片
    隐私政策
  • 原文地址:https://www.cnblogs.com/haostyle/p/13185759.html
Copyright © 2020-2023  润新知